Home » Java programming language

User Login System in Servlet and JSP by MVC pattern using MySQL

By: Vanka Manikanth, on 22 JAN 2017

This is a Login System which contains user registration and login with the same registration details. Here, we are using both the Servlet and JSP in an MVC pattern.

Index.jsp

Taking all the inputs from user and sending them to Controller Servlet in Form Action.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>Login System</title>
		<style>
			#regform{
			text-align:justify;
			padding:15px 15px;
			background-color:#003366;
			height:400px;
			border-radius:15px;
			}
			td{
			width:100px;
			color:white;
			}
			p{

			text-align:center;
			font-size:16pt;
			color:#000066;
			}
			h1{
			margin:25px;
			text-align:center;
			background-color:#003366;
			color:#fff;
			}
		</style>
	</head>
	<body>
	<h1>User Login System in Servlet and Jsp by MVC pattern using MySQL</h1>
	<form action="controller" method="post">
		<p>SignUp Here</p>
		<table id="regform" cellspacing="20" align="center">
		<tr><td>USER ID :</td><td><input type="text" id="id" name="userid" placeholder="Enter only digits" required="required"></td></tr>
		<tr><td>USERNAME:</td><td><input type="text" name="username" placeholder="Enter Alphabetics only" required></td></tr>
		<tr><td>PASSWORD:</td><td> <input type="password" name="password" placeholder="Enter your password" required></td></tr>
		<tr><td>EMAIL:</td><td> <input type="email" name="email" placeholder="Enter your email" required></td></tr>
		<tr><td colspan=5 align="center"><button type="submit">REGISTER</button></td></tr></table>
		<p>Already Registered ?? Then,<a href="login.jsp">Login Here</a></p>
	</form>
</body>
</html>

• Create com.dbconnection for Dbconnection.java

• Create com.controller for ControllerServlet.java

• Create com.operations for LoginServlet.java, SaveUser.java and UserLoginValidate.java

• Create com.pojo for UserPojo.java

Dbconnection.java

Here we are creating DbConnection and return the Connection.

package com.dbconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Dbconnection {
	public static Connection getConnection() throws SQLException{ //making a static connection,shares to all classes
		Connection con=null; // creating connection
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con=DriverManager.getConnection("jdbc:mysql://localhost:3306/regform","root","root");
						
		} catch (Exception e) {
			con.close();
			//throws an error if at all its unable to create an connection
			System.out.println(e);
		}	
		return con; // we return the connection and we can get the connection wherever needed.
	}		
}

ControllerServlet.java

Here we are taking all the values entered by user in Index.jsp and sending to its corresponding method save method.

package com.controller;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.operations.SaveUser;
import com.pojo.UserPojo;


public class ControllerServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		resp.setContentType("text/html");
		PrintWriter out=resp.getWriter();
		try {
			String userid =req.getParameter("userid");
			int id= Integer.parseInt(userid);
			String username=req.getParameter("username"); //getting all the values from user
			String pass=req.getParameter("password");
			String email=req.getParameter("email");
			//getting all the values from index.jsp
			
			UserPojo pObject = new UserPojo();
			pObject.setId(id);
			pObject.setUsername(username);		//setting up the received values from index.jsp to setters and getters
			pObject.setPass(pass);
			pObject.setEmail(email);
			
			
			
			int status = SaveUser.save(pObject); // sending the pObject values to save method
			if(status>0){
			//executes if the details are added to database
				out.print("<h2 align='center'>SuccessFully Registered</h2>"); // if successfully executes save method
				out.print("<a align='center'href='login.jsp'>Login Here</a>");
				
				
			}else{
				req.getRequestDispatcher("index.jsp").include(req, resp);
				out.print("<p>User Already Exists with Same User Details</p>");

				//this executes if user is already exists
			}
			
		}catch(Exception e){
			req.getRequestDispatcher("index.jsp").include(req, resp);

			out.print("<p>Enter Valid Details to Register</p>");
			// executes if at all user enters invalid details
		}		
	}
}

UserPojo.java

Here we use encapsulation technique by defining the private variables and implementing the public setters and getters to it.

package com.pojo;

public class UserPojo {
	private int id;
	private String username,pass,email;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}	
}

SaveUser.java

Here we are inserting all the details into database.

package com.operations;

import java.sql.Connection;
import java.sql.PreparedStatement;


import com.dbconnection.Dbconnection;
import com.pojo.UserPojo;

public class SaveUser {

	public static int save(UserPojo pObject){
		int flag=0;
		try {
			Connection con=Dbconnection.getConnection(); //getting the connection method here from dbconnection
			PreparedStatement ps = con.prepareStatement("insert into reginfo values(?,?,?,?);");
			ps.setInt(1, pObject.getId());
			ps.setString(2, pObject.getUsername());//sending up the values received from user to the database table
			ps.setString(3, pObject.getPass());
			ps.setString(4, pObject.getEmail());
			flag=ps.executeUpdate(); //value changes if it is executed
			con.close();
		} catch (Exception e) {
		System.out.println(e);
		}
		return flag; // returns greater than zero if inserted into database
	}	
}

Login.jsp

This is login page, give the User id and Password which you have been registered at the registration page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title>login Page</title>
		<style>
		h1{
		color:green;
		text-decoration: underline;
		text-align: center;

		}
		form{
		border:2px solid green;
		margin: 5em;
		}
		p{
		text-align:center;
		font-size: 16pt;
		}
		</style>
	</head>
	<body>
		<h1>Login Page</h1>
		<form action="LoginServlet" method="post">
			<table id="loginform" cellspacing="20" align="center">
			<tr><td>USER ID :</td><td><input type="text" id="id" name="userid" placeholder="Enter only digits" required="required"></td></tr>
			<tr><td>PASSWORD:</td><td> <input type="password" name="password" placeholder="Enter your password" required></td></tr>
			<tr><td colspan=5 align="center"><button type="submit">Login</button></td></tr></table>
		</form>
	</body>
</html>

LoginServlet.java

Here we are taking the input values from Login.jsp and sending them to UserLoginValidate.java.

package com.operations;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.pojo.UserPojo;




public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter out = resp.getWriter();

		try{
			String uid=req.getParameter("userid");
			int id=Integer.parseInt(uid); //getting userid and password from user 
			String password =req.getParameter("password");	
			
			UserPojo pObject = new UserPojo();
		
			pObject.setId(id);  //setting them to setters and getters
			pObject.setPass(password);
			List<UserPojo>list = new ArrayList<>(); //take a list
			

			  list =UserLoginValidate.getUsers(id, password); //send the values id and password to vadlidate class of getUsers method and storing the resultset in list
			 if(!(list.isEmpty())){
				 //if list has some values then you are logged in
			 out.print("<h1 align='center'>Congrats!You've SuccessFully Logged In</h1>");
				 out.print("<table align ='center' border='1' cellspacing='5' cellpadding='5'><tr><th>ID</th><th>NAME</th><th>Password</th><th>Email</th></tr>");
			    for(UserPojo i:list){	 	 
			    	//printing all the values in the list
			         out.print("<tr><td>" +i.getId()+ "</td>");
			         out.print("<td>" +i.getUsername()+ "</td>");
			         out.print("<td>" +i.getPass()+ "</td>");
			         out.print("<td>" +i.getEmail()+"</td></tr>");
			    }
		out.print("</table>");
		
			 }else{
		     //if no values are found then the User does not exist
		            req.getRequestDispatcher("login.jsp").include(req, resp);
		            out.print("<p align='center'>User Does Not Exist! Please Register");
			         out.print("<a href='index.jsp'>Register Here</a></p>");
			 }
		}catch(Exception e){
            req.getRequestDispatcher("login.jsp").include(req, resp);
            out.print("<p>Please Enter Valid Details To Login</p>");
//executes when user enters invalid details
			
		}
	}

}

UserLoginValidate.java

Here we are validating the details which are entered at Login.jsp, if the details exist in database then it gives the total list of user details registered else it would return empty.

package com.operations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


import com.dbconnection.Dbconnection;

import com.pojo.UserPojo;

public class UserLoginValidate {
	public static List<UserPojo> getUsers(int id,String password){		
		List<UserPojo>list = new ArrayList<>();
		//take a list to store the values which are in db
		 try{  
			Connection con=Dbconnection.getConnection();  
			PreparedStatement ps=con.prepareStatement("select * from reginfo where id=? and password=?");  
			ps.setInt(1,id);  
			ps.setString(2,password);
			ResultSet rs=ps.executeQuery();  
			if(rs.next()){  				
				UserPojo pObject=new UserPojo(); 
				pObject.setId(rs.getInt(1));  
				pObject.setUsername(rs.getString(2)); //if the values exist in db then											
				pObject.setPass(rs.getString(3));     // set them to setters and getters and them to list and return the list finally
				pObject.setEmail(rs.getString(4));
				list.add(pObject);
			}  
			con.close();  
		}catch(Exception ex){ex.printStackTrace();}  		  
		return list;  //returns the list		
	}
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>LoginSystem</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Form</servlet-name>
    <servlet-class>com.controller.ControllerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Form</servlet-name>
    <url-pattern>/controller</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>LoginServletr</servlet-name>
    <servlet-class>com.operations.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServletr</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>

OUTPUT

User Login System in Servlet and JSP by MVC pattern using MySQL

User Login System in Servlet

User Login System in Servlet and JSP

Login System in Servlet and JSP




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.