Login and logout with JSP and Servlet with MYSQL

How to perform login and logout in a Java web project using JSP, Servlet, and MYSQL. In this JPS and Servlet tutorial, we are going to create a simple Java web application to perform Login and Logout.

Before starting login and logout with JSP and servlet please take a look at login and registration in JSP activity. 

Login and Logout with JSP and Servlet with Mysql

Let’s create a simple Java web project to Login and Logout. there will be one home page(home.JSP), login page(login.JSP) and Welcome page(WelcomeUser.JSP).

When the user enters the user name and password from the login page and clicks on the login button. then If it’s valid user page will be redirected to the welcome page otherwise it will send an error message “Invalid username and password”.

The session will be used to perform login and logout in JSP and servlet. At the time of user login will create a session that will be unique for every user and the session will be invalidated at the time of logout. Get more details about the session in JSP.

Configure MYSQL database

Create a new database with the name “mydb” and table name “user_reg”.

CREATE TABLE `mydb`.`user_reg` (
  `uid` INT NOT NULL AUTO_INCREMENT,
  `uname` VARCHAR(45) NULL,
  `upass` VARCHAR(45) NULL,
  `uemail` VARCHAR(45) NULL,
  PRIMARY KEY (`uid`));

Create Home Page(home.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Login and Lgout activity using JSP</h1>
<a href="http://localhost:8080/loginDemo/home.jsp"> Home</a>
<a href="http://localhost:8080/loginDemo/login.jsp"> Login</a>
<a href="http://localhost:8080/loginDemo/logout.jsp"> Logout</a>
</body>
</html>

Create login page (login.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

  <h1>Login Here</h1>

  <form action="UserProfile" method="post">
    <pre>
UserName: <input type="text" name="uname">

Password: <input type="text" name="upass">

    <input type="submit" value="Login">

</pre>
  </form>


</body>
</html>

Create Welcome Page (WelcomeUser.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% 
request.getSession(false);
if (session == null) { %>
  <a href="http://localhost:8080/loginDemo/home.jsp"> Home</a>
  <a href="http://localhost:8080/loginDemo/login.jsp"> Login</a>
  <% 
} else {
    // Already created.
    %>
  <a href="http://localhost:8080/loginDemo/logout.jsp"> Logout</a><% 
}

String name = request.getParameter("name");
%>
<br><br>

<%

out.println("Welcome: "+name);
%>



</body>
</html>

UserProfile.java(Servlet)

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class UserProfile
 */
@WebServlet("/UserProfile")
public class UserProfile extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserProfile() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
    PrintWriter out = response.getWriter();
    String uname = request.getParameter("uname");
    String upass = request.getParameter("upass");
    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select uname,upass from user_reg where uname='"+uname+"' and upass='"+upass+"'");
      
      if(rs.next()) {
        response.sendRedirect("http://localhost:8080/loginDemo/WelcomeUser.jsp?name="+rs.getString("uname"));
        HttpSession session = request.getSession();
        session.setAttribute("uname", uname);
        
        
      }else {
        out.println("Wrong id and password");
      }
      
      
      
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
    
    
  }

}

Login and logout with JSP and servlet with Mysql(Video tutorial)

Here is a complete video tutorial with practicals that will show you how to create a java application and connect it with MSQL a database. or an idea for java database connectivity(JDBC) with MySQL so please watch the complete video first.

Used tool and Technologies in this Java web example

Database:    MySQL workbench.
Language: HTML or JSP,servlet.
Server:         Glassfish or Tomcat.

Practise Task in JSP

One Reply to “Login and logout with JSP and Servlet with MYSQL”

Leave a Reply

Your email address will not be published.