Build a Java Jsp Login Example
Login Example with JSP + Servlet + JDBC + MySQL Database
In this tutorial, we will build a simple Login Form using JSP, Servlet, JDBC and MySQL database.
In this example, we will create an Employee Login Form and we will validate employee username and password with the MySQL database.
Create an Eclipse Dynamic Web Project
To create a new dynamic Web project in Eclipse:
1. On the main menu selectFile > New > Project....
2. In the upcoming wizard chooseWeb > Dynamic Web Project.
3. ClickNext.
4. Enter project name as "login-jsp-servlet-jdbc-example";
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.
Add Dependencies
Add the below jars files to the lib folder.
- jsp-api.2.3.1.jar - servlet-api.2.3.jar - mysql-connector-java-8.0.13.jar
In Eclipse, paste these JAR files to your project directory:WebContent/WEB-INF/lib
MySQL Database Setup
Let's create a database named "mysql_database" in MySQL. Now, create a login table using below DDL script:
CREATE TABLE `login` ( `username` varchar(45) NOT NULL, `password` varchar(45) DEFAULT NULL, PRIMARY KEY ( `username` ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Here is an Insert SQL statement:
INSERT INTO `mysql_database` . `login` ( `username` , `password` ) VALUES ( "Ramesh" , "Ramesh" );
Create a JavaBean - LoginBean.java
Let's create aLoginBean class which we will use in JSP action tags.
package net.javaguides.login.bean; import java.io.Serializable; public class LoginBean implements Serializable { /** * */ private static final long serialVersionUID = 1 L; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this .username = username; } public String getPassword() { return password; } public void setPassword(String password) { this .password = password; } }
Create a LoginDao.java
Let's create a LoginDao class which contains JDBC code to connect with MySQL database. Add the following code to a LoginDao class:
package net.javaguides.login.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import net.javaguides.login.bean.LoginBean; public class LoginDao { public boolean validate(LoginBean loginBean) throws ClassNotFoundException { boolean status = false; Class .forName( "com.mysql.jdbc.Driver" ); try (Connection connection = DriverManager .getConnection( "jdbc:mysql://localhost:3306/mysql_database?useSSL=false" , "root" , "root" ); // Step 2:Create a statement using connection object PreparedStatement preparedStatement = connection .prepareStatement( "select * from login where username = ? and password = ? " )) { preparedStatement.setString(1, loginBean.getUsername()); preparedStatement.setString(2, loginBean.getPassword()); System .out.println(preparedStatement); ResultSet rs = preparedStatement.executeQuery(); status = rs.next(); } catch (SQLException e) { // process sql exception printSQLException(e); } return status; } private void printSQLException(SQLException ex) { for (Throwable e: ex) { if (e instanceof SQLException) { e.printStackTrace(System .err); System .err.println( "SQLState: " + ((SQLException) e).getSQLState()); System .err.println( "Error Code: " + ((SQLException) e).getErrorCode()); System .err.println( "Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System .out.println( "Cause: " + t); t = t.getCause(); } } } } }
Create a LoginServlet.java
Let's createLoginServlet to process HTTP request parameters and redirect to the appropriate JSP page based on the employee login status. If login successfully validated with the database then redirect tologinsuccess.jsp page otherwise redirect tologin.jsp page.
package net.javaguides.login.web; import java.io.IOException; 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; import net.javaguides.login.bean.LoginBean; import net.javaguides.login.database.LoginDao; /** * @email Ramesh Fadatare */ @WebServlet( "/login" ) public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1 L; private LoginDao loginDao; public void init() { loginDao = new LoginDao(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter( "username" ); String password = request.getParameter( "password" ); LoginBean loginBean = new LoginBean(); loginBean.setUsername(username); loginBean.setPassword(password); try { if (loginDao.validate(loginBean)) { //HttpSession session = request.getSession(); // session.setAttribute("username",username); response.sendRedirect( "loginsuccess.jsp" ); } else { HttpSession session = request.getSession(); //session.setAttribute("user", username); //response.sendRedirect("login.jsp"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
Let's createLoginServlet to process HTTP request parameters and redirect to the appropriate JSP page based on the employee login status. If login successfully validated with the database then redirect tologinsuccess.jsp page otherwise redirect tologin.jsp page.
package net.javaguides.login.web; import java.io.IOException; 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; import net.javaguides.login.bean.LoginBean; import net.javaguides.login.database.LoginDao; /** * @email Ramesh Fadatare */ @WebServlet( "/login" ) public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1 L; private LoginDao loginDao; public void init() { loginDao = new LoginDao(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter( "username" ); String password = request.getParameter( "password" ); LoginBean loginBean = new LoginBean(); loginBean.setUsername(username); loginBean.setPassword(password); try { if (loginDao.validate(loginBean)) { //HttpSession session = request.getSession(); // session.setAttribute("username",username); response.sendRedirect( "loginsuccess.jsp" ); } else { HttpSession session = request.getSession(); //session.setAttribute("user", username); //response.sendRedirect("login.jsp"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
Create a login.jsp
Let's design login HTML form with following fields:
- username
- password
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <!DOCTYPE html> <html> <head> <meta charset= "ISO-8859-1" > <title>Insert title here</title> </head> <body> <div align= "center" > <h1>Employee Login Form</h1> <form action= " <%= request.getContextPath() %>/login" method= "post" > <table style= " with: 100% " > <tr> <td>UserName</td> <td><input type= "text" name= "username" /></td> </tr> <tr> <td>Password</td> <td><input type= "password" name= "password" /></td> </tr> </table> <input type= "submit" value= "Submit" /> </form> </div> </body> </html>
Create a loginsuccess.jsp
After an employee successfully login then this page shows a successful message on screen:
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@page import= "net.javaguides.login.database.*" %> <!DOCTYPE html> <html> <head> <meta charset= "ISO-8859-1" > <title>Insert title here</title> </head> <body> <div align= "center" > <h1>You have logined successfully</h1> </div> </body> </html>
Note that in the above page, we have used JSP action tags. Read more about action tags here.
Demo
It's time to see a demo of the above development. Deploy this web application in tomcat server.
Employee Login Form
Login Success Page
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course
Source: https://www.sourcecodeexamples.net/2020/05/login-example-with-jsp-servlet-jdbc-mysql-example.html
0 Response to "Build a Java Jsp Login Example"
Post a Comment