Servlet realizes login function

Keywords: Java JSP servlet

Servlet realizes login function

Title:

Create a project, use servlet a to complete a login page, and when the user enters the user name and password on the login page, send it to servlet B,
After servlet B obtains the user name and password, it creates a correct user name and password in the Web.xml file as shared static data in advance
Servlet B obtains the shared static data and matches the user name and password sent by the browser. If the matching is successful, it returns the successful login of the browser
If it does not match, jump to ServletC and display "login failed, user name does not exist or password error, please click here to log in again, or automatically jump to the login page after 5 seconds".

What this problem wants to master -- the four objects of Servlet.

analysis:

Step 1:

First create a Servlet a, and then use the response object in the Servlet to complete a login page. The specific codes are as follows:

package com.Servlet.HomeWorks;

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

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

/**
 * The Servlet is used to display the page effect of the browser login function
 * Servlet implementation class ServletA
 */
@WebServlet("/SerA")
public class ServletA extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletA() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Set encoding format
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		//Create a login page
		PrintWriter pw = response.getWriter();
		pw.print("<div align='center'>");
		pw.print("<h1>User login</h1>");
		//Create a form
		pw.print("<form action='SerB' method='get'>");
		pw.print("user name:<input type='text' name='userName'>&nbsp;");
		pw.print("dense		Code:<input type='text' name='passWord'>&nbsp;<br /><br />");
		pw.print("<input type='submit' value='Sign in'>&nbsp;");
		pw.print("</form>");
		pw.print("</div>");
		
		//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);
	}

}

The result after running is: the login page is displayed.

Step 2:

Before creating ServletB, configure the sharable static data in the web.xml configuration file in advance. The function of the static data is to determine the basis when the user logs in. The specific codes are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>JSP_HomeWorks</display-name>
  <welcome-file-list>
  	<welcome-file>index.jsp</welcome-file>
    <welcome-file>Bio.jsp</welcome-file>
    <welcome-file>OldBio.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- Set the shared static data - user name and password in advance -->
  <context-param>
  	<param-name>name</param-name>
  	<param-value>Yu Wenjun</param-value>
  </context-param>
  <context-param>
  	<param-name>password</param-name>
  	<param-value>20020525</param-value>
  </context-param>
  <!-- Note: These data are ultimately used to verify whether the user name and password are equal to the existing account -->
</web-app>

After that, the user name and password obtained from servlet a are judged with the sharable static data prepared in advance. If the user name and password match, the prompt "browser login succeeded" will be displayed on the browser; If the user name and password do not match, jump to ServletC. The specific codes are as follows:

package com.Servlet.HomeWorks;

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

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

/**
 * The Servlet is used to display the effect after the user enters the user name and password
 * Requirements:
 * 	When the user name and password entered by the user are consistent, the prompt message of successful login of the browser will be displayed;
 * 	When the user name and password entered by the user do not match, jump to another page,
 * 		The effect displayed on this page is:
 * 			Display "user name does not exist or password error";
 * 			And please click here to log in again or automatically jump to the login page after 5 seconds.
 * Servlet implementation class ServletB
 */
@WebServlet("/SerB")
public class ServletB extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletB() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Set encoding format
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		String userNames = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		//pw.print(userNames + "---" + passWord);
		//Verify user name and password:
		/**
		 * If the user name and password are consistent with the data of existing users, a prompt message will be displayed - successful browser login;
		 * If not, it will jump to the next page and display "login failed, user name does not exist or password error",
		 * And the following functions are realized:
		 * 	Please log in again here, or automatically jump to the login page after 5 seconds.
		 */
		//The first is to get the shared static data in the configuration file
		//The data is used as a sign of judgment
		//Create a ServletContext object
		ServletContext context = getServletContext();
		String name = context.getInitParameter("name");
		String password = context.getInitParameter("password");
		//Judge
		if(name.equals(userNames) && password.equals(passWord)) {
			//When the user name and password entered by the user are consistent, the prompt of successful login will be displayed
			pw.print("<h1>Browser login succeeded!</h1>");
		}else {
			//When the user name and password do not match, jump to another page
			response.sendRedirect("SerC");
		}
		
		//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);
	}

}

Step 3:

Finally, create a Servlet C, which is used to display the page after login failure. The effect is to display the prompt message of "login failed, user name does not exist or password error", and realize the function of returning to the login page by clicking or automatically jumping back to the login page by 5 seconds. The specific codes are as follows:

package com.Servlet.HomeWorks;

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

import javax.servlet.ServletContext;
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.xml.ws.Response;
import javax.xml.ws.soap.AddressingFeature.Responses;

/**
 * The Servlet is used to display the effect of browser login failure
 * Purpose:
 * 	The effect displayed on this page is:
 * 			Display "user name does not exist or password error";
 * 			And please click here to log in again or automatically jump to the login page after 5 seconds.
 * Servlet implementation class ServletC
 */
@WebServlet("/SerC")
public class ServletC extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletC() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		//When you jump to this page, it indicates that the browser login failed
		//Set the prompt information in advance
		String info = "<h1 style='color:red;'>Login failed, user name does not exist or password error!</h1>";
		//Then a prompt message of login failure will be sent
		PrintWriter pw = response.getWriter();
		//Output prompt information
		pw.print(info);
		
		//Mode 1:
		//Please click here to login again
		//PW. Print ("< a href ='sera '> please log in again < br >");
		
		//Mode 2:
		//Automatically jump to the login page after 5 seconds
		//Create a ServletContext object
		ServletContext context = getServletContext();
		//Create a variable to represent the time remaining
		int number = 5;
		Object ob = context.getAttribute("time");
		if(ob == null) {
			context.setAttribute("time", number);
		}else {
			number = Integer.parseInt(ob + "");
			context.setAttribute("time", number != 0 ? number - 1 : 5);
			if(number == 0) response.sendRedirect("SerA");
		}
		response.getWriter().write("Back to the login page Countdown:" + number + "S");
		response.setHeader("refresh", "1");
		
		//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);
	}

}

The a tag is used here to realize "jump back to the login page after clicking"; For the 5-second countdown, jump back to the login page. If you don't understand, you can refer to my previous blog. < auto jump to page in five seconds >.

Summary:

For this problem, the difficulty is not too great. However, you must master the four basic objects of Servlet - ServletConfig, ServletContext, response and request.

Posted by Plasma on Sat, 23 Oct 2021 07:14:59 -0700