[Servlet] Automatic login for three days of request forwarding, redirection and Cookie usage

Keywords: Java encoding Database github

Three-day automatic landing project source code: GitHub address - LoginSystem

  • JDBC
  • Handwritten SORM Framework
  • Handwritten Servlet
  • Development environment: Eclipse

1. Solving the problem of scrambling requests

		// Setting the request and response encoding format
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

2. Summary of Servlet's Use Process

The Use Process of Servlet

(1) Setting the request encoding format
(2) Setting the response encoding format
(3) Obtaining request information
(4) Processing request information
(5) Response processing results

Data flow process

Browser - --> Server - ---- - > Database
Browser < - - - Server < - - - Database

3. Request forwarding, redirection, Cookie learning notes

1. Request forwarding

Questions:
When the server receives the browser's request, it only uses one Servlet to process the request, which will result in different redundancy of the Servlet logic code, and the responsibility of the Servlet is not clear.

Solve:
Use request forwarding.

	// Request forwarding
	req.setAttribute("str", "ERROR Incorrect username or password");
	req.getRequestDispatcher("PageServlet").forward(req, resp);
	return;

Characteristic:
A request
Address bar information remains unchanged.

Request object scope in request forwarding

Questions:
How can data be shared between different servlets after request forwarding? Or how does data flow from one servlet to another?

Solve:
Scope using request object

Use:

//servlet to send request
request.setAttribute(Object name,Object value);

//servlet receiving request
request.getAttribute(Object obj);

Effect:
The problem of sharing data (request data + other data) among different servlets in a request is solved.

Scope:
Based on request forwarding, all servlets in a request are shared.

Be careful:
Request objects are used for data flow, and the data is valid only in one request.

Characteristic:
Server creation
Each request is created
Life cycle one request

2. Redirection

Questions:
What if the current request cannot be processed by the Servlet?
What if request forwarding causes duplicate submission of form data?

Solve:
Making Redirections

Use:
Respons. sendRedirect ("path").
The local path is:uri
The network path is: directed resource URL information

Characteristic:
Two requests
Browser Address Bar Information Change
Avoid duplicate submission of forms

3,Cookie

At present, we all have an understanding of the interaction mode between browser and server, as well as the processing of requests, and can also handle requests. This lesson focuses on the whole process of technology optimization again, focusing on learning Cookie technology, the application of this technology is very wide.

Questions:
HTTP protocol has no memory function, after a request, the relevant data will be destroyed.
What if the second request needs to use the same request data?
Is it to ask the user to write again?

Solve:
Using Cookie Technology

Explanation:
Cookie technology is actually a data storage technology on browser side, which solves the problem that different requests need to use the same request data.
We store the request data that requests need to be shared in the browser side to avoid users repeating the written request data.
But which data needs to be stored using Cookie technology is a subjective problem. It needs to tell the browser when it responds in the background. Some data will be used in other requests and need to be stored.

Characteristic:
Data Storage Technology on Browser Side
Suitable for small amounts of data
Key-value pairs
Unsafe

Use:

(1) Cookie data storage:

  • Temporary Storage: No cookie information storage time is set, cycle is a session, stored in browser memory
  • Timing Storage: Set the storage time, the period is time set, stored in the user's computer.
Cookie c = new Cookie("uid", ((User) result).getUid() + "");
			c.setMaxAge(5 * 60);// Timed storage for 5 minutes
			c.setPath("CookieServlet");
			resp.addCookie(c);

(2) Cookie data acquisition:

Cookie[] cks = req.getCookies();

Summary:
Cookie technology solves the problem of data sharing between different requests.

4. Cookie Learning Case is exempt from login for three days

(1)PageServlet.java

Used to print html login pages

package cn.hanquan.servlet;

import java.io.IOException;

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

public class PageServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		resp.setContentType("text/html;charset=utf-8");

		String str = (String) req.getAttribute("str") == null ? "" : (String) req.getAttribute("str");// Error prompt
		resp.getWriter().write("<html>");
		resp.getWriter().write("<head>");
		resp.getWriter().write("</head>");
		resp.getWriter().write("<body>");
		resp.getWriter().write("<font color='red' size='20px'>" + str + "</font>");
		resp.getWriter().write("<form action='LoginServlet' method='get'>");
		resp.getWriter().write("User name:<input type='text' name='uname' value=''/><br/>");
		resp.getWriter().write("Password:<input type='password' name='upwd' value=''/><br/>");
		resp.getWriter().write("<input type='submit'  value='Sign in'/><br/>");
		resp.getWriter().write("</form>");
		resp.getWriter().write("</body>");
		resp.getWriter().write("</html>");
	}
}

(2)MainServlet.java

Welcome interface after successful landing

package cn.hanquan.servlet;

import java.io.IOException;

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

public class MainServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// Setting the request and response encoding format
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

		// Getting Request Information
		// Processing request information
		// Response processing results
		resp.getWriter().write("<html>");
		resp.getWriter().write("<head>");
		resp.getWriter().write("</head>");
		resp.getWriter().write("<body>");
		resp.getWriter().write("<h3>Welcome " + req.getParameter("uname") + " Visiting Shang School Management System</h3>"); // Only request forwarding is valid
		resp.getWriter().write("<hr>");
		resp.getWriter().write("</body>");
		resp.getWriter().write("</html>");
	}
}

(3)LoginServlet.java

Detection interface after clicking login button

  • If direct access/login fails, redirect to the Page Servlet page
  • If the login is successful, redirect to the MainServlet page
package cn.hanquan.servlet;

import java.io.IOException;

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

import cn.hanquan.orm.core.Query;
import cn.hanquan.orm.core.QueryFactory;
import cn.hanquan.orm.po.User;

public class LoginServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// Setting the request and response encoding format
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

		// Getting Request Information
		String uname = req.getParameter("uname");
		String upwd = req.getParameter("upwd");
		System.out.println("Obtained uname=" + uname + "upwd=" + upwd);

		// Processing request information
		if (uname == null || upwd == null) {// Avoid direct access to the null pointer on this page
			resp.sendRedirect("PageServlet");
			return;
		}
		User u = new User();
		u.setUname(uname);
		u.setUpwd(upwd);

		Query q = QueryFactory.createQuery();
		Object result = q.queryUniqueRow("select * from user where uname=? and upwd=?", User.class,
				new String[] { uname, upwd });
		System.out.println(result);

		// Logon results
		if (result != null) {// right
			Cookie c = new Cookie("uid", ((User) result).getUid() + "");
			c.setMaxAge(5 * 60);
			c.setPath("CookieServlet");
			resp.addCookie(c);
			// Request forwarding
			req.setAttribute("uname", u.getUname());
			req.getRequestDispatcher("MainServlet").forward(req, resp);
//			// Redirection
//			resp.sendRedirect("MainServlet");
			return;
		} else {// wrong
			// Request forwarding
			req.setAttribute("str", "ERROR Incorrect username or password");
			req.getRequestDispatcher("PageServlet").forward(req, resp);
			return;
		}
	}
}

(4)CookieServlet

Cache Detection Interface

  • If there is a cached data uid for the previous logged-in record, verify the existence of the user twice and redirect to the MainServlet page
package cn.hanquan.servlet;

import java.io.IOException;

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

import cn.hanquan.orm.core.Query;
import cn.hanquan.orm.core.QueryFactory;
import cn.hanquan.orm.po.User;

public class CookieServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

		Cookie[] cks = req.getCookies();
		if (cks != null) {
			String uid = "";
			for (Cookie c : cks) {
				if ("uid".equals(c.getName())) {
					uid = c.getValue();
				}
			}

			if ("".equals(uid)) {// Partial cookie s are deleted by users
				req.setAttribute("str", "You cleaned it up cookie Do you");
				req.getRequestDispatcher("page").forward(req, resp);
				return;
			} else {// Secondary Authentication of User Existence
				User u = new User();
				u.setUid(Integer.parseInt(uid));
				Query q = QueryFactory.createQuery();
				Object result = q.queryUniqueRow("select * from user where uid=?", User.class, new String[] { uid });

				if (result != null) {
					resp.sendRedirect("MainServlet");
					return;
				} else {
					req.setAttribute("str", "You don't seem to be in the database anymore.");
					req.getRequestDispatcher("/PageServlet").forward(req, resp);
					return;
				}
			}
		} else {
			req.getRequestDispatcher("page").forward(req, resp);
			return;
		}
	}
}

5. Examples of Operation Effect

(1) Database table structure

(2) Login page

(3) Successful login result page

Posted by toyartist on Mon, 19 Aug 2019 22:49:52 -0700