1: Filter chain
Multiple Filter programs can be registered in a Web application, and each Filter program can intercept a URL. If multiple Filter programs intercept the same URL, these filters will form a Filter chain (also known as Filter chain). The Filter chain is represented by the FilterChain object. There is a doFilter () method in the FilterChain object, which is used to release the current Filter on the Filter chain and make the request enter the next Filter. Next, a legend is used to describe the interception process of the Filter chain, as shown in the figure
In Figure 8-6, when the browser accesses resources in the Web server, it needs to go through two filters, Filter1 and Filter2. First, Filer1 will intercept the request. After processing the request in the Filter1 filter, pass the request to fiter2 by calling the doFilter () method of Filter1 Filter2 also calls the doFilter () method after processing the user request, and finally sends the request to the target resource. When the Web server responds to this request, it will also be intercepted by the filter. This interception order is opposite to that before, and finally the response result will be sent to the client.
(1) In the CN. Itcast. chapter08.filter package of chapter08 project, create two narrators MyFilter01 and MyFilter02,
MyFilter01.java
package cn.itcast.chapter08.filter; import java.io.*; import javax.servlet.*; public class MyFilter01 implements Filter { public void init(FilterConfig fConfig) throws ServletException { // The filter object is called during initialization, and some initialization parameters can be configured } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // It is used to intercept the user's request. If it matches the interception path of the current filter, this method will be called PrintWriter out=response.getWriter(); out.write("Hello MyFilter01<br />"); chain.doFilter(request, response); } public void destroy() { // The filter object is automatically called when it is destroyed to release resources } }
MyFilter02.java
package cn.itcast.chapter08.filter; import java.io.*; import javax.servlet.Filter; import javax.servlet.*; public class MyFilter02 implements Filter { public void init(FilterConfig fConfig) throws ServletException { // The filter object is called during initialization, and some initialization parameters can be configured } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // It is used to intercept the user's request. If it matches the interception path of the current filter, this method will be called PrintWriter out=response.getWriter(); out.write("MyFilter02 Before<br />"); chain.doFilter(request, response); out.write("<br />MyFilter02 After<br />"); } public void destroy() { // The filter object is automatically called when it is destroyed to release resources } }
In order to prevent other filters from affecting the demonstration effect of the Filter chain, please first on the web Comment out the configuration information of other filters in the XML file. Then, configure the mapping information of MyFiter01 and MyFilter02 filters in front of the MyServlet configuration information
<filter> <filter-name>MyFilter01</filter-name> <filter-class>cn.itcast.chapter009.filter.MyFilter01</filter-class> </filter> <filter-mapping> <filter-name>MyFilter01</filter-name> <url-pattern>/MyServlet</url-pattern> </filter-mapping> <filter> <filter-name>MyFilter02</filter-name> <filter-class>cn.itcast.chapter08.filter.MyFilter02</filter-class> </filter> <filter-mapping> <filter-name>MyFilter02</filter-name> <url-pattern>/MyServlet</url-pattern> </filter-mapping> <servlet> <description></description> <display-name>MyServlet</display-name> <servlet-name>MyServlet</servlet-name> <servlet-class>cn.itcast.chapter08.filter.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</url-pattern> </servlet-mapping>
result
The MServlet is first intercepted by MyFilterO1, prints out the content in MyFIter01, and then intercepted by MyFiler02. The browser does not display the output content in the MServlet until myrvlet is intercepted by MyFiler02.
2: FilterConfig interface;
MyFilter03.java
package cn.itcast.chapter08 .filter; import java.io.*; import javax.servlet.*; public class MyFilter03 implements Filter { private String characterEncoding; FilterConfig fc; public void init(FilterConfig fConfig) throws ServletException { // Get FilterConfig object this.fc = fConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Output parameter information characterEncoding=fc.getInitParameter("encoding"); System.out.println("encoding The values of initialization parameters are:"+characterEncoding); chain.doFilter(request, response); } public void destroy() { } }
In order to prevent other filters from affecting the interception effect of MyFiter03, the MyFiler03 mapping information is configured on the web XML file at the front end,
<filter> <filter-name>MyFilter03</filter-name> <filter-class>cn.itcast.chapter08.filter.MyFilter03</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>MyFilter03</filter-name> <url-pattern>/MyServlet</url-pattern> </filter-mapping>
result
3: Automatic login of real users using Filter
Cookie can realize the function of automatic user login. When the user accesses the server for the first time, the server will send a cookie containing user information. After that, when the client accesses the server again, the cookie will be sent back together with the server. In this way, the server can obtain user information from cookies, so as to realize the automatic login function of users, as shown in the figure.
It can be seen that after using cookies to realize the automatic login of users, when the client accesses the server's Servlet, all servlets need to verify the Cookie information of the product, which is bound to lead to a large number of duplicate codes written in the Servlet program.
To solve the above problems, you can implement Cookie verification in the Filer program. Since Firer can intercept all requests from the server, once the request passes the Filter program, it is equivalent to passing the user information verification, and the Serviet program checks the user information according to the obtained user information. You can log in automatically.
1. Write User class:
package chapter08.entity; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2. Realize the login page and home page:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.util.*"%> <html> <head></head> <center><h3>User login</h3></center> <body style="text-align: center;"> <form action="${pageContext.request.contextPath }/LoginServlet" method="post"> <table border="1" width="600px" cellpadding="0" cellspacing="0" align="center" > <tr> <td height="30" align="center">user name:</td> <td> <input type="text" name="username" />${errorMsg }</td> </tr> <tr> <td height="30" align="center">dense Code:</td> <td> <input type="password" name="password" /></td> </tr> <tr> <td height="35" align="center">Automatic login time</td> <td><input type="radio" name="autologin" value="${60*60*24*31 }" />one month <input type="radio" name="autologin" value="${60*60*24*31*3 }" />three months <input type="radio" name="autologin" value="${60*60*24*31*6 }" />half a year <input type="radio" name="autologin" value="${60*60*24*31*12 }" />a year </td> </tr> <tr> <td height="30" colspan="2" align="center"> <input type="submit" value="Sign in" /> <input type="reset" value="Reset" /> </td> </tr> </table> </form> </body> <html>
Write index JSP page, which is used to display users
Login information for. If no user logs in, a hyperlink for user login will be displayed in the index jp page
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.util.*" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Displays the logged in user information</title> </head> <body> <br /> <center> <h3>Welcome</h3> </center> <br /> <c:choose> <c:when test="${sessionScope.user==null }"> <a href="http://localhost:8080/chap08/login. JSP "> user login</a> </c:when> <c:otherwise> Welcome: ${sessionScope.user.username} <a href="http://Localhost: 8080 / Chap08 / logoutservlet "> Exit</a> </c:otherwise> </c:choose> <hr /> </body> </html>
3. Create a Servlet
Write the LoginServlet class
package chapter08.entity; import java.io.IOException; 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; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //Get user name and password String username = request.getParameter("username"); String password = request.getParameter("password"); //Check user name and password if ("itcast".equals(username) && "123456".equals(password)) { //Login succeeded //Save the user state user object into the session domain User user = new User(); user.setUsername(username); user.setPassword(password); request.getSession().setAttribute("user", user); //Send automatic login cookie String autoLogin = request.getParameter("autoLogin"); if (autoLogin != null) { //Note the encryption in cookie s Cookie cookie = new Cookie(autoLogin, username + "-"+password); cookie.setMaxAge(Integer.parseInt(autoLogin)); cookie.setPath(request.getContextPath()); response.addCookie(cookie); } //Jump to home page response.sendRedirect(request.getContextPath()+"/index.jsp"); }else { request.setAttribute("errerMsg", "Wrong user name or password"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } /** * @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); } }
Write the LogoutServlet class
package chapter08.entity; import java.io.IOException; 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 jdk.javadoc.doclet.Reporter; /** * Servlet implementation class LogoutServlet */ public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LogoutServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //User logout request.getSession().removeAttribute("user"); //Delete automatic login cookie from client Cookie cookie=new Cookie("autologin", "msg"); cookie.setPath(request.getContextPath()); cookie.setMaxAge(0); response.addCookie(cookie); response.sendRedirect(request.getContextPath()+"/index.jsp"); } /** * @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); } }
4. Create a filter
package chapter08.entity; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; /** * Servlet Filter implementation class AutoLoginFilter */ public class AutoLoginFilter implements Filter { /** * Default constructor. */ public AutoLoginFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest) req; // place your code here // pass the request along the filter chain //Get a cookie named autologin Cookie[] cookies = request.getCookies(); String autologin = null; for (int i = 0; cookies != null && i<cookies.length;i++) { if ("autologin".equals(cookies[i].getValue())) { autologin = cookies[i].getValue(); break; } } if (autologin != null) { //Do automatic login String[] parts = autologin.split("-"); String username = parts[0]; String password = parts[1]; //Check user name and password if ("itcast".equals(username)&&("123456").equals(password)) { //Log in successfully, and save the user status user object into the session domain User user = new User(); user.setUsername(username); user.setPassword(password); request.getSession().setAttribute("user", user); } } //Release chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
5. Configure mapping information
<filter-mapping> <filter-name>AutoLoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>cn.itcast.chapter08.filter.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>cn.itcast.chapter08.filter.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/LogoutServlet</url-pattern> </servlet-mapping>
6. Run the project and view the results