Java Web Implementation login registration

1. Introduction

I believe that just learning Javaweb partners first contact with personal small projects are from the project login registration began. The login registration section in the next mini-project will teach you how to design the login registration process from scratch.

2. Log in and register the design process

3. Registered data flow

So how do we get data from the front end to the back end? 1. First of all, we use form pass to submit through form

Here, we input our name and password and click the register button. The three inputs, which we can see as a form of data, will be submitted to the server:

3. At this point, something called Tomcat handles the request,

4. Once the request is received, Tomcat sends the request to the Servlet for processing

5.Servlet calls various implementation methods written by the Dao layer and interacts with the database (CURD calls)

So here is the main call flow diagram for the registration operation

graph LR
A[register.jsp]  --> B[registServlet]  --> C[ UserDB] 

The first step

The second step

The third step

4. Login data flow

Flowchart for the main invocation of a login operation

graph LR
A[Login.jsp]  --> B[LoginServlet]  --> C[ UserDB] 

The first step

The second step

The third step

The fourth step

5. Part of the code display

5.1 registered

The register.jsp registration page jumps to a servlet via a form implementation

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width",initial->
    <link rel="stylesheet" href="style.css">
    <title>world message board of the future</title>
</head>

<body background="pictures/02.jpg">
<div class="form-wrapper">
    <div class="header">
        Register
	</div>
	<form action="RegistServlet" method = "post"> <! When the viewer clicks the Send button to send the form, the hidden field information is also sent to the server. --> <input type="hidden" name="action" value="regist">
    <div class="input-wrapper">
    	<div class="border-wrapper">
        	<input type="text" name="username" placeholder="username" class="border-item">
    	</div>
        <div class="border-wrapper">
            <input type="text" name="password" placeholder="password" class="border-item">
		</div>
	<div class="border-wrapper">
		<input type="password" name="password2" placeholder="Confirm password" class="border-item">
	</div>
	<div class="action">
		<input type="submit" name="regist" class="btn" value="Regist"><br> </div> </div> </form> <center> <! --> <pclass="col">${message}</p>
	</center>
	</div>
</body>
</html>
Copy the code

The Registerservlet.java business layer: Handles the registration business

package Sevlet;

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 javaBean.User;
import useBean.UserDB;

@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	String message ="";
       
    public RegistServlet(a) {
        super(a); }protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// Get information about the hidden domain
		String action = request.getParameter("action");
		String url ="register.jsp";
		
		if(action.equals("regist")) 
			url = registerUser(request,response);
		getServletContext().getRequestDispatcher(url).forward(request, response);
	}
	// Register the function
	private String registerUser(HttpServletRequest request,HttpServletResponse response) {
		String username = request.getParameter("username"); 
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		String message = "";
		// Get an object of type HttpSession
		HttpSession session = request.getSession();
		// Store the data in the User object
		User user = new User();
		user.setusername (username); 
		user.setpassword(password);
		String url = "/login.jsp";
		if(password.equals(password2))
		{
			if( !UserDB.UserExists(username) ) {
				message = "Registration successful! and login in";
				session.setAttribute("message", message);
				// Write the registered user to the database
				UserDB.insert(user);
				return url;
			}
			else
			{
				message = "The user name already exists";
				url = "/register.jsp";
				session.setAttribute("message", message);
				returnurl; }}else 
		{
			message = "The password is inconsistent";
			session.setAttribute("message", message);
			url = "/register.jsp";
			returnurl; }}}Copy the code

The Dao layer implements the method userdb.java to determine whether a user name exists and insert it into the database

    // Check whether the user name exists during registration
	public static boolean UserExists(String username) {
		// You can set up a connection pool to hold a certain number of connections. When an object needs a database connection, the connection is returned directly to the object.
		ConnectionPool pool = ConnectionPool.getInstance();
		Connection connection = pool.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String qr = "SELECT username FROM User "+ "WHERE username = ?";
		try {
			ps = connection.prepareStatement(qr);
			ps.setString(1, username);
			rs = ps.executeQuery();
			return rs.next();
		} catch (SQLException e) {
			System.out.println(e);
			return false;
		} finally{ DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); }}// Save registered user information to database
	public static int insert(User user) {
		ConnectionPool pool = ConnectionPool.getInstance();
		Connection connection = pool.getConnection();
		PreparedStatement ps = null;
		
		String qr = "INSERT INTO User (username, password)"+"VALUES (? ,?) ";
		try { 
			
			ps = connection.prepareStatement(qr);
			ps.setString(1, user.getusername());
			ps.setString(2, user.getpassword());
			
			return ps.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e);
			return 0;
		} finally{ DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); }}Copy the code

5.2 the login

The login.jsp login interface jumps to a servlet through a form

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width",initial->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="style.css">
    <title>world message board of the future</title>
</head>

<body background="pictures/01.jpg">
<div class="form-wrapper">
    <div class="header">
        login
	</div>
	<form action="LoginServlet" method = "post"> <! When you submit the form, it goes to LoginServlet --> <! When the viewer clicks the Send button to send the form, the hidden field information is also sent to the server. --> <input type="hidden" name="action" value="login">
    <div class="input-wrapper">
    	<div class="border-wrapper">
        	<input type="text" name="username" placeholder="input username" class="border-item">
    	</div>
        <div class="border-wrapper">
            <input type="password" name="password" placeholder="password" class="border-item">
        </div>
      
    </div>
	<div class="action">
		<input type="submit" name="login" class="btn" value="Sign in" ><br>
		<button type="submit" formaction="register.jsp"  class="btn">register</button> </div> </form> <center> <! --> <pclass="col">${message}</p>
	</center>
</div>
</body>
</html>
Copy the code

Loginservlet. Java business layer: Handles login services

package Sevlet;

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

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

import javaBean.Message;
import javaBean.User;
import useBean.UserDB;
/** * Servlet implementation class Login */
@WebServlet("/LoginServlet")// Read /LoginServlet full path
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	String message="";// Define a variable
    public LoginServlet(a) {
        super(a); }protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url ="/login.jsp";
		String action = request.getParameter("action");
		System.out.println("action: " + action);// Print tests
		// Set the encoding
		request.setCharacterEncoding("utf-8");
		// Check if the page is committed
		if(action == null)
			url="/login.jsp";
		else if(action.equals("login"))
		// Calling login() returns a path
			url = login(request,response);
		// Set a message indicating whether the login is successful
		request.setAttribute("message", message);
		// Call the forward() method to forward the request
		getServletContext().getRequestDispatcher(url).forward(request, response);
	}
	
	/ / the login () function
	private String login(HttpServletRequest request, HttpServletResponse response) {
		// Get login information (name and password)
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// Get an object of type HttpSession
		HttpSession session = request.getSession();
		String userid="";
		// Get user information by name
		User user = UserDB.selectUser(username);

		String url = "/register.jsp";
		if(user ! =null) {
			// The user exists
			if(user.getpassword().equals(password)) {
				// Records the user status
				//cookie adds the user name
				Cookie u = new Cookie("userid",username);
				// Set the validity period
				u.setMaxAge(60*60*24*365*2);
				// Set the path
				u.setPath("/");
				// Add cookies to the browser
				response.addCookie(u);
				
				userid = user.getid();
				session.setAttribute("userid", userid);
				// Call selectU to read all data from the message table
				List<Message> mL = UserDB.selectU(); 
				// Returns ml information
				request.setAttribute("MessageList", mL);
				url="/MessageList.jsp";
				
			}
			else {
				message = "Wrong password";
				url="/login.jsp"; }}else {
			message = "The user does not exist";
			url = "/login.jsp";
		}
		returnurl; }}Copy the code

The UserDB.java Dao layer implements db.java, a method to find users

	
	// Read user according to username during login
	public static User selectUser(String username) {
		// You can set up a connection pool to hold a certain number of connections. When an object needs a database connection, the connection is returned directly to the object.
		ConnectionPool pool = ConnectionPool.getInstance();
		Connection connection = pool.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		/ / SQL statements
		String qr = "SELECT * FROM User "+ "WHERE username = ?";
		try {
			ps = connection.prepareStatement(qr);
			// SQL statement question mark interpretation
			ps.setString(1, username);
			rs = ps.executeQuery();
			User user = null;
			if (rs.next()) {
				user = new User ();
				// Set userd's ID,username,passward
				user.setid(rs.getString("id"));
				user.setusername(rs.getString("username"));
				user.setpassword(rs.getString("password"));
			}
			return user;
		} catch (SQLException e) {
			System.out.println(e);
			return null;
			} finally {
				// Close PreparedStatement and ResultSet and release the connection from the connection poolDBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); }}Copy the code

6. Summary

All the above login source code from my project, interested partners can leave a message in the comment area. I am willing to share my study with you. Welcome criticism and correction!