In this tutorial, I will teach you how to do login using JSP script. The following example will give you a clear and detailed explanation of JSP login script. We will use eclipse editor for code writing and MySQL as the database. Another thing we required, i.e, mysql_connector.jar file. It should be copied into the WebContent\WEB-INF\lib folder.
Database table
Create the user_login table in the database and insert the below rows into that table.
CREATE TABLE IF NOT EXISTS `user_login` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) INSERT INTO `user_login` (`id`, `username`, `password`, `name`) VALUES (1, 'user123', '123456', 'Mitrajit Samanta'), (2, 'user456', '456789', 'Sachin Tendulkar');
Database configuration
Create a JSP page db.jsp and write the following contents in it.
<%@ page import="java.sql.*" %> <% java.sql.Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","username","password"); } catch (Exception e) { out.println(e.getMessage()); } %>
You need to import the “java.sql.*” to perform any query related operation. Class.forName loads the appropriate driver class for the MySQL database. DriverManager.getConnection(…) method creates the connection between the JSP and the MySQL.
Complete code – Login using JSP
Create index.jsp page and write the below contents in it. The following code contains HTML login form where users can input their username and password for authentication.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ include file="db.jsp" %> <!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>Login using JSP example -- Mitrajit's Tech Blog </title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <h1>Read the full article -- <a href="http://www.mitrajit.com/2016/12/login-using-jsp-example/" target="_blank">Login using JSP example</a> in <a href="http://www.mitrajit.com" target="_blank"></a>Mitrajit's Tech Blog</a></h1> <% //Remove any session attribute if present session.removeAttribute("name"); String msg = ""; String button = request.getParameter("submitBtn"); if(button != null && button.equals("Login")) { String username = request.getParameter("username").trim(); String password = request.getParameter("password").trim(); if(username.length() > 0 && password.length() > 0) { Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from user_login where username='"+username+"' and password='"+password+"'"); if(rs.next()) { session.setAttribute("name", rs.getString("name")); response.sendRedirect("welcome.jsp"); } else { msg = "Invalid username and password!"; } } else { msg = "Both fields are required!"; } } %> <div class="loginWrapper"> <h2>ADMIN PANEL</h2> <form action="" method="post"> <label>Username : </label><input type="text" name="username" id="username" value=""/> <label>Password : </label><input type="password" name="password" id="password" value=""/> <input type="submit" name="submitBtn" id="submitBtn" value="Login" align="middle"/> <span><%=msg %></span> </form> </div><!-- end of .loginWrapper --> </body> </html>
The session.removeAttribute(…) removes any session attribute if present. In the java code, we will receive the form data by using request.getParameter(…) method. Based on the inputted username and password, a query will execute and return the user’s details if any match found otherwise it will return nothing. session.setAttribute(…) method sets the returned value from the table to a session variable. We can access this session variable from any JSP page. response.sendRedirect(…) method redirects to the welcome.jsp page if any match found.
CSS
Create a CSS file styles.css within the css folder and write the below code in it.
body, html { padding:0; margin:0; } h1 { clear:both; margin-bottom:30px; font-size:17px; } h1 a { font-weight:bold; color:#0099FF; } .loginWrapper { position:absolute; margin: auto; top:0; left:0; bottom:0; right:0; width:415px; height:200px; border:1px solid #000; padding:10px 20px; } H2 { margin: 0; text-align: center; font-size: 17px; border-bottom: 2px solid #000; margin-bottom:20px; } label { display:block; clear:both; paddind-bottom:5px; } #username, #password { width:400px; margin-bottom:20px; padding:3px 5px; } #submitBtn { width:100px; padding:5px 20px; margin-right:20px; } span { color:#ff0000; font-weight: bold; }
welcome.jsp
Create another JSP page welcome.jsp and write the below code in it.
<% String name = (String) session.getAttribute("name"); if(name != null && name.length() > 0) { out.println("Welcome "+ session.getAttribute("name")); } else { response.sendRedirect("index.jsp"); } %>
If any session attribute is set and it is not null then we will just display the name of the user, otherwise, the page redirects to the index.jsp page.
You can download the complete source code from the download link below and please like and share the tutorial link to others.