Filter, filter , seeing the name of a thing one thinks of its function , It's the filtering of data , Pretreatment process . Why introduce filters ? When you visit a website , Sometimes send sensitive information , When it is displayed after sending out You'll use sensitive information with * And so on , That's how the information is processed with filters . This is just a simple example , Of course , Filters are so powerful , Its function can't be limited to this , It can not only prepare for Data processing , As long as the request is sent, it can be preprocessed , meanwhile , It can also preprocess the response returned by the server , such , Greatly reduces the pressure on the server . for example , Realization URL Grade Access control 、 Filter sensitive words 、 Compress response information and other advanced functions . Let's introduce the filter in detail .

One 、 Definition

Learn a thing , We need to understand its definition first .

1. Concept

Filtration , Filter the requests sent from client to server , You can also process the response returned by the server . It allows users to change a request And modify a response..Filter Is not a servlet, It can't produce a response, But it can be in a request arrive servlet Pretreatment before request, It can also be in response Leave servlet Time processing response. let me put it another way ,filter It's actually the client and servlet The one in the middle , And it can deliver To modify something .

Be careful : Filters are used to intercept requests and responses , No response , and servlet It's used to process requests and generate responses .

2. Applicable occasions

Realization URL Level of access control , Filter sensitive words , Compress response information, etc .

3. How filters implement interception

  • When the client requests , stay HttpServletRequest arrive Servlet Before , The filter intercepts the customer's HttpServletRequest .
  • Check as needed HttpServletRequest , You can also modify HttpServletRequest Head and data .
  • It is called in the filter doFilter Method , To ask for release . Request arrival Servlet after , Process the request and produce HttpServletResponse Send to client .
  • stay HttpServletResponse Before reaching the client , Filter intercept HttpServletResponse .
  • Check as needed HttpServletResponse , You can modify HttpServletResponse Head and data .
  • Last ,HttpServletResponse To the client .

4.Filter Interface

Servlet API Provides a Filter Interface , The filter written must implement this interface .

5.Filter Life cycle of

(1)Filter There are three important methods in the interface .

  • init() Method : Initialize parameters , Creating Filter Automatically call . When we need to set initialization parameters , It can be written into this method .
  • doFilter() Method : When a request to be executed is intercepted ,doFilter Will execute . It's about our preprocessing of requests and responses .
  • destroy() Method : In the process of destruction Filter Automatically call .

(2)Filter Life cycle of

 Filter Created and destroyed by web Server control .

  • When the server starts ,web Server creation Filter Instance object of , And call it init Method , Complete the initialization function of the object .filter Object will only be created once ,init The method will only be executed once .
  • When a request is intercepted , perform doFilter Method . It can be executed multiple times .
  • When the server is down ,web Server destruction Filter Instance object of .

6.Filter object ——FilterConfig

use User in configuration filter when , have access to <init-param> by filter Configure some initialization parameters , When web Container instantiation Filter object , Call its init When the method is used , It will encapsulate filter Initializing parameters filterConfig The object passed in . So the developers are writing filter when , adopt filterConfig Object method , You can get :

  • String getFilterName(): obtain filter The name of .
  • String getInitParameter(String name): Returns the value of the initialization parameter with the name specified in the deployment description . Returns if none exists null.
  • Enumeration getInitParameterNames(): Returns an enumeration set of the names of all initialization parameters of the filter .
  • public ServletContext getServletContext(): return Servlet References to context objects .

7. Filter chain ——FilterChain

A set of filters for some web Resources to intercept , This set of filters is called a filter chain . The execution order of the filter and <filter-mapping> of ( Who is the first to execute who ).

Two 、 Development steps

Understand the concept of filter , Next, we will develop an example .

1. Writing steps

  • To write java Class implementation Filter Interface , And realize it doFilter Method .
  • stay web.xml Use... In the document <filter> and <filter-mapping> Element pair filter Class to register , And set the resources it can intercept .

2. Example

(1) ordinary Filter Example

  • To write FilterDemo1 class
 1 package com.oracle.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11
12 public class FilterDemo1 implements Filter{
13
14 /*
15 * Yes Filter The whole life cycle of
16 * matters needing attention :
17 * 1. Realization Filter Interface is javax.servlet.Filter package
18 * 2. All the methods are web The server automatically calls , We don't have to call... Manually
19 * 3.init Methods usually write initialization parameters , There's no need to , Use the following example again .
20 * 4.destroy Methods generally don't need to write any code
21 * 5. rewrite doFilter Method , We can write our processing actions for intercepted requests and responses .
22 * 6. After writing this class, configure filter, stay web.xml Middle configuration .
23 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
24 */
25 @Override
26 public void init(FilterConfig filterConfig) throws ServletException {
27 // TODO Auto-generated method stub
28 System.out.println("FilterDemo1 Of init Method is called ");
29 }
30
31 @Override
32 public void doFilter(ServletRequest request, ServletResponse response,
33 FilterChain chain) throws IOException, ServletException {
34 // TODO Auto-generated method stub
35 System.out.println(" I am a FilterDemo1, Client to Servlet The request I sent was intercepted ");
36 chain.doFilter(request, response);
37 System.out.println(" I am a FilterDemo1,Servlet The response sent to the client was intercepted by me ");
38 }
39
40 @Override
41 public void destroy() {
42 // TODO Auto-generated method stub
43 System.out.println("FilterDemo1 Of destroy Method is called ");
44 }
45
46 }
  • To configure filter, stay web.xml Add the following code to the file
1 <filter>
2 <filter-name>filterDemo1</filter-name>
3 <filter-class>com.oracle.filter.FilterDemo1</filter-class>
4 </filter>
5 <filter-mapping>
6 <filter-name>filterDemo1</filter-name>
7 <url-pattern>/*</url-pattern>
8 <!-- /* Is to intercept all the files -->
9 </filter-mapping>
  • Console results

  • branch Analysis : As can be seen from the above results , When the server starts , It's called init Method , When visiting the page , The filter intercepts request execution doFilter Method , In this method , Use doFilter Method , When the response is returned , Continue with the rest of the code , After the execution, the response is passed to the client . When you shut down the server , The server calls destroy Method .

(2)Filter Chain example

  • To write FilterDemo1 class
 1 package com.oracle.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11
12 public class FilterDemo1 implements Filter{
13
14 /*
15 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
16 */
17 @Override
18 public void init(FilterConfig filterConfig) throws ServletException {
19 // TODO Auto-generated method stub
20 }
21
22 @Override
23 public void doFilter(ServletRequest request, ServletResponse response,
24 FilterChain chain) throws IOException, ServletException {
25 // TODO Auto-generated method stub
26 System.out.println(" I am a FilterDemo1, Client to Servlet The request I sent was intercepted ");
27 // To ask for release , Go to the next filter FilterDemo2
28 chain.doFilter(request, response);
29 System.out.println(" I am a FilterDemo1,Servlet The response sent to the client was intercepted by me ");
30 }
31
32 @Override
33 public void destroy() {
34 // TODO Auto-generated method stub
35 }
36
37 }
  • To write FilterDemo2 class
 1 package com.oracle.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11
12 public class FilterDemo2 implements Filter{
13
14 @Override
15 public void init(FilterConfig filterConfig) throws ServletException {
16 // TODO Auto-generated method stub
17
18 }
19
20 @Override
21 public void doFilter(ServletRequest request, ServletResponse response,
22 FilterChain chain) throws IOException, ServletException {
23 // TODO Auto-generated method stub
24 System.out.println(" I am a FilterDemo2, Client to Servlet The request I sent was intercepted ");
25 // To ask for release , Get into Servlet
26 chain.doFilter(request, response);
27 System.out.println(" I am a FilterDemo2,Servlet The response sent to the client was intercepted by me ");
28 }
29
30 @Override
31 public void destroy() {
32 // TODO Auto-generated method stub
33
34 }
35
36 }
  • To configure filter, stay web.xml Add the following code to the file
 1 <filter>
2 <filter-name>filterDemo1</filter-name>
3 <filter-class>com.oracle.filter.FilterDemo1</filter-class>
4 </filter>
5 <filter>
6 <filter-name>filterDemo2</filter-name>
7 <filter-class>com.oracle.filter.FilterDemo2</filter-class>
8 </filter>
9
10 <filter-mapping>
11 <filter-name>filterDemo1</filter-name>
12 <url-pattern>/*</url-pattern>
13 <!-- /* Is to intercept all the files -->
14 </filter-mapping>
15 <filter-mapping>
16 <filter-name>filterDemo2</filter-name>
17 <url-pattern>/*</url-pattern>
18 <!-- /* Is to intercept all the files -->
19 </filter-mapping>
  • Console results

  • branch Analysis : When multiple filters intercept the same request , according to web.xml In file <filter-mapping> Configuration order , Who is ahead , Who's going to do it first . When the first After a successful filter interception , Will execute doFilter Method , In this method , call chain.doFilter Method , The request will be released to the next filter , Execute sequentially , Until the execution of To the last filter , When the last filter calls chain.doFilter When the method is used , The request will be released to Servlet, When Servlet When processing return response information , Go back first Back to the last filter executed , Continue with the rest of the code for the filter . Go back to , Until you go back to the first filter , Finally return to the client .

 (3) Disable cache filters for all dynamic pages

  • To write FilterDemo3 class
 1 package com.oracle.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletResponse;
12
13 public class FilterDemo3 implements Filter{
14
15 @Override
16 public void init(FilterConfig filterConfig) throws ServletException {
17 // TODO Auto-generated method stub
18
19 }
20
21 @Override
22 public void doFilter(ServletRequest request, ServletResponse response,
23 FilterChain chain) throws IOException, ServletException {
24 // stay response The head set Cache-Control、Pragma and Expires You can cancel the cache
25 HttpServletResponse resp = (HttpServletResponse)response;
26 resp.setHeader("Cache-Control", "no-cache");
27 resp.setHeader("Pragma", "no-cache");
28 resp.setDateHeader("Expires", -1);
29 chain.doFilter(request, resp);
30 }
31
32 @Override
33 public void destroy() {
34 // TODO Auto-generated method stub
35
36 }
37
38 }
  • To configure filter, stay web.xml Add the following code to the file
1 <filter>
2 <filter-name>filterDemo3</filter-name>
3 <filter-class>com.oracle.filter.FilterDemo3</filter-class>
4 </filter>
5
6 <filter-mapping>
7 <filter-name>filterDemo3</filter-name>
8 <url-pattern>/*</url-pattern>
9 </filter-mapping>

(4) branch IP Statistics website visits filter

  • To write FilterDemo4 class
 1 package com.oracle.filter;
2
3 import java.io.IOException;
4 import java.util.HashMap;
5 import java.util.Map;
6
7 import javax.servlet.Filter;
8 import javax.servlet.FilterChain;
9 import javax.servlet.FilterConfig;
10 import javax.servlet.ServletContext;
11 import javax.servlet.ServletException;
12 import javax.servlet.ServletRequest;
13 import javax.servlet.ServletResponse;
14
15 public class FilterDemo4 implements Filter{
16
17 private FilterConfig filterConfig;
18 @Override
19 public void init(FilterConfig filterConfig) throws ServletException {
20 // TODO Auto-generated method stub
21
22 // Initialize parameters ,ipCount For storage ip And the number of visits
23 ServletContext application = filterConfig.getServletContext();
24 Map<String,Integer> ipCount = new HashMap<String,Integer>();
25 application.setAttribute("ipCount",ipCount);
26 this.filterConfig = filterConfig;
27 }
28
29
30 @Override
31 public void doFilter(ServletRequest request, ServletResponse response,
32 FilterChain chain) throws IOException, ServletException {
33 // TODO Auto-generated method stub
34 ServletContext application = filterConfig.getServletContext();
35 Map<String,Integer> ipCount = (HashMap<String,Integer>)application.getAttribute("ipCount");
36 String ip = request.getRemoteAddr();
37 Integer count = ipCount.get(ip);
38 if(count != null){
39 //Map There is the ip
40 count = count + 1;
41 }else{
42 count = 1;
43 }
44 ipCount.put(ip, count);
45 application.setAttribute("ipCount",ipCount);
46 chain.doFilter(request, response);
47 }
48
49 @Override
50 public void destroy() {
51 // TODO Auto-generated method stub
52
53 }
54
55 }
  • To write index.jsp page
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
6 %>
7
8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
9 <html>
10 <head>
11 <base href="<%=basePath%>">
12
13 <title>My JSP 'index.jsp' starting page</title>
14 <meta http-equiv="pragma" content="no-cache">
15 <meta http-equiv="cache-control" content="no-cache">
16 <meta http-equiv="expires" content="0">
17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18 <meta http-equiv="description" content="This is my page">
19 <!--
20 <link rel="stylesheet" type="text/css" href="styles.css">
21 -->
22 </head>
23
24 <body>
25 <h1> branch IP Statistics website visits </h1>
26 <table border="1" width="400">
27 <tr>
28 <th>IP Address </th>
29 <th> Browse times </th>
30 </tr>
31 <c:forEach items="${ipCount}" var="m">
32 <tr>
33 <td>${m.key}</td>
34 <td>${m.value}</td>
35 </tr>
36 </c:forEach>
37 </table>
38 </body>
39 </html>
  • To configure filter, stay web.xml Add the following code to the file
1 <filter>
2 <filter-name>filterDemo4</filter-name>
3 <filter-class>com.oracle.filter.FilterDemo4</filter-class>
4 </filter>
5
6 <filter-mapping>
7 <filter-name>filterDemo4</filter-name>
8 <url-pattern>/*</url-pattern>
9 </filter-mapping>
  • Web results

(5) automatic logon

  • To write AutoLoginFilter class
 1 package com.oracle.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.Cookie;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpSession;
14
15 import com.oracle.biz.UserInfoBiz;
16 import com.oracle.biz.impl.UserInfoBizImpl;
17 import com.oracle.entity.UserInfo;
18 import com.oracle.util.CookieUtil;
19
20 public class AutoLoginFilter implements Filter{
21
22 @Override
23 public void init(FilterConfig filterConfig) throws ServletException {
24 // TODO Auto-generated method stub
25
26 }
27
28 @Override
29 public void doFilter(ServletRequest request, ServletResponse response,
30 FilterChain chain) throws IOException, ServletException {
31 // TODO Auto-generated method stub
32 // First judge session Whether there is , If it exists, let it go , If it doesn't exist, judge cookie Whether the user name and password exist in , If it exists, query the database to see if it is correct , If it is right, it will be deposited in session And release , If it is not correct, it will be released
33 HttpServletRequest req = (HttpServletRequest)request;
34 HttpSession session = req.getSession();
35 UserInfo user = (UserInfo)session.getAttribute("user");
36 if(user != null){
37 chain.doFilter(req, response);
38 }else{
39 //session There is no user in
40 Cookie[] cookies = req.getCookies();
41 Cookie cookie = CookieUtil.findCookie(cookies, "autoLogin");
42 if(cookie!=null){
43 // stay cookie Found the user
44 UserInfoBiz ubiz = new UserInfoBizImpl();
45 String name = cookie.getValue().split("#oracle#")[0];
46 String pwd = cookie.getValue().split("#oracle#")[1];
47 String msg = ubiz.login(name, pwd);
48 if(" Landing successful !".equals(msg)){
49 user = ubiz.getByName(name);
50 session.setAttribute("user", user);
51 chain.doFilter(req, response);
52 }else{
53 chain.doFilter(req, response);
54 }
55 }else{
56 // The customer was not found
57 chain.doFilter(req, response);
58 }
59 }
60 }
61
62 @Override
63 public void destroy() {
64 // TODO Auto-generated method stub
65
66 }
67
68
69 }
  • To write DoLoginServlet
 1 package com.oracle.servlet;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.http.Cookie;
7 import javax.servlet.http.HttpServlet;
8 import javax.servlet.http.HttpServletRequest;
9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11
12 import com.oracle.biz.UserInfoBiz;
13 import com.oracle.biz.impl.UserInfoBizImpl;
14 import com.oracle.entity.UserInfo;
15
16 public class DoLoginServlet extends HttpServlet {
17
18 /**
19 * Constructor of the object.
20 */
21 public DoLoginServlet() {
22 super();
23 }
24
25 /**
26 * Destruction of the servlet. <br>
27 */
28 public void destroy() {
29 super.destroy(); // Just puts "destroy" string in log
30 // Put your code here
31 }
32
33 /**
34 * The doGet method of the servlet. <br>
35 *
36 * This method is called when a form has its tag value method equals to get.
37 *
38 * @param request the request send by the client to the server
39 * @param response the response send by the server to the client
40 * @throws ServletException if an error occurred
41 * @throws IOException if an error occurred
42 */
43 public void doGet(HttpServletRequest request, HttpServletResponse response)
44 throws ServletException, IOException {
45
46 doPost(request,response);
47 }
48
49 /**
50 * The doPost method of the servlet. <br>
51 *
52 * This method is called when a form has its tag value method equals to post.
53 *
54 * @param request the request send by the client to the server
55 * @param response the response send by the server to the client
56 * @throws ServletException if an error occurred
57 * @throws IOException if an error occurred
58 */
59 public void doPost(HttpServletRequest request, HttpServletResponse response)
60 throws ServletException, IOException {
61
62 HttpSession session = request.getSession();
63 request.setCharacterEncoding("UTF-8");
64 response.setCharacterEncoding("UTF-8");
65 String name = request.getParameter("myname");
66 String pwd = request.getParameter("pwd");
67 String autoLogin = request.getParameter("autoLogin");
68 UserInfoBiz ubiz = new UserInfoBizImpl();
69 //ubiz.login(name, pwd): Judge whether the user has logged in successfully , Returns a string . Return on success " Landing successful !", If it is not successful, the corresponding error prompt will be returned .
70 String msg = ubiz.login(name, pwd);
71 if(" Landing successful !".equals(msg)){
72 UserInfo user = ubiz.getByName(name);
73 session.setAttribute("user", user);
74 if("true".equals(autoLogin)){
75 // utilize cookie Remember the user name and password
76 Cookie cookie = new Cookie("autoLogin",user.getUserName()+"#oracle#"+user.getPassword());
77 // Set the effective time
78 cookie.setMaxAge(60*60*24);
79 // take cookie Write back to browser
80 response.addCookie(cookie);
81 }
82 response.sendRedirect("success.jsp");
83 }else{
84 request.setAttribute("msg", msg);
85 request.getRequestDispatcher("login.jsp").forward(request, response);
86 }
87 }
88
89 /**
90 * Initialization of the servlet. <br>
91 *
92 * @throws ServletException if an error occurs
93 */
94 public void init() throws ServletException {
95 // Put your code here
96 }
97
98 }
  • To write CookieUtil
 1 package com.oracle.util;
2
3 import javax.servlet.http.Cookie;
4
5
6
7 public class CookieUtil {
8
9 public static Cookie findCookie(Cookie[] cookies,String name){
10 if(cookies==null){
11 return null;
12 }else{
13 for(Cookie cookie:cookies){
14 if(cookie.getName().equals(name)){
15 return cookie;
16 }
17 }
18 return null;
19 }
20 }
21 }
  • To write login.jsp
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%
3 String path = request.getContextPath();
4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
5 %>
6
7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
8 <html>
9 <head>
10 <base href="<%=basePath%>">
11
12 <title>My JSP 'login.jsp' starting page</title>
13
14 <meta http-equiv="pragma" content="no-cache">
15 <meta http-equiv="cache-control" content="no-cache">
16 <meta http-equiv="expires" content="0">
17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18 <meta http-equiv="description" content="This is my page">
19 <!--
20 <link rel="stylesheet" type="text/css" href="styles.css">
21 -->
22
23 </head>
24
25 <body>
26 <form action="doLogin" method="post">
27 user name <input name="myname"><br/>
28 The secret &nbsp; code <input type="password" name="pwd"><br/>
29 <input type="checkBox" name="autoLogin" value="true"> automatic logon <br/>
30 <input type="submit" value=" land ">
31 </form>
32 </body>
33 </html>
  • To write success.jsp
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
3 <%
4 String path = request.getContextPath();
5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
6 %>
7
8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
9 <html>
10 <head>
11 <base href="<%=basePath%>">
12
13 <title>My JSP 'success.jsp' starting page</title>
14
15 <meta http-equiv="pragma" content="no-cache">
16 <meta http-equiv="cache-control" content="no-cache">
17 <meta http-equiv="expires" content="0">
18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19 <meta http-equiv="description" content="This is my page">
20 <!--
21 <link rel="stylesheet" type="text/css" href="styles.css">
22 -->
23
24 </head>
25
26 <body>
27 <c:if test="${empty user}">
28 <h2> You haven't logged in yet , Please go <a href="login.jsp"> land </a></h2>
29 </c:if>
30 <c:if test="${not empty user}">
31 <h2> Welcome ${user.userName}</h2>
32 </c:if>
33 </body>
34 </html>
  • To configure filter and servlet, stay web.xml Add the following code to the file
 1 <servlet>
2 <description>This is the description of my J2EE component</description>
3 <display-name>This is the display name of my J2EE component</display-name>
4 <servlet-name>DoLoginServlet</servlet-name>
5 <servlet-class>com.oracle.servlet.DoLoginServlet</servlet-class>
6 </servlet>
7
8 <servlet-mapping>
9 <servlet-name>DoLoginServlet</servlet-name>
10 <url-pattern>/doLogin</url-pattern>
11 </servlet-mapping>
12
13 <filter>
14 <filter-name>AutoLoginFilter</filter-name>
15 <filter-class>com.oracle.filter.AutoLoginFilter</filter-class>
16 </filter>
17 <filter-mapping>
18 <filter-name>AutoLoginFilter</filter-name>
19 <url-pattern>/*</url-pattern>
20 </filter-mapping>

(6) Deal with the website's Get and Post Ask for random code

  • thinking road : enhance request Object's getParameter Methods and so on . Write a class MyHttpServletRequest Realization HttpServletRequestWrapper, Rewrite its getParameter Methods and so on , In these methods, the data submitted in different ways are transcoded . Filtering In the device , take request Cast to MyHttpServletRequest Object of type , such , When used again getParameter When you wait for a method, you actually call Your rewritten getParametr Method , That is, the data that has been processed , In this way, you don't have to worry about garbled code any more .
  • MyHttpServletRequest class
 1 package com.oracle.bookshop.filter;
2
3 import java.io.UnsupportedEncodingException;
4 import java.util.Map;
5
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletRequestWrapper;
8
9
10 public class MyHttpServletRequest extends HttpServletRequestWrapper {
11 /*
12 * This class rewrites
13 */
14 private HttpServletRequest request;
15
16 private boolean hasEncode;
17
18 public MyHttpServletRequest(HttpServletRequest request) {
19 super(request);// super Must write
20 this.request = request;
21 }
22
23 // Covering the methods that need to be enhanced
24 @Override
25 public Map getParameterMap() {
26 // Get the request first
27 String method = request.getMethod();
28 if (method.equalsIgnoreCase("post")) {
29 // post request
30 try {
31 // Handle post The statement
32 request.setCharacterEncoding("utf-8");
33 return request.getParameterMap();
34 } catch (UnsupportedEncodingException e) {
35 e.printStackTrace();
36 }
37 } else if (method.equalsIgnoreCase("get")) {
38 // get request
39 Map<String, String[]> parameterMap = request.getParameterMap();
40 if (!hasEncode) { // Make sure get The manual encoding logic only runs once
41 for (String parameterName : parameterMap.keySet()) {
42 String[] values = parameterMap.get(parameterName);
43 if (values != null) {
44 for (int i = 0; i < values.length; i++) {
45 try {
46 // Handle get The statement
47 values[i] = new String(values[i]
48 .getBytes("ISO-8859-1"), "utf-8");
49 } catch (UnsupportedEncodingException e) {
50 e.printStackTrace();
51 }
52 }
53 }
54 }
55 hasEncode = true;
56 }
57 return parameterMap;
58 }
59
60 return super.getParameterMap();
61 }
62
63 @Override
64 public String getParameter(String name) {
65 Map<String, String[]> parameterMap = getParameterMap();
66 String[] values = parameterMap.get(name);
67 if (values == null) {
68 return null;
69 }
70 return values[0]; // Get the first value of the parameter
71 }
72
73 @Override
74 public String[] getParameterValues(String name) {
75 Map<String, String[]> parameterMap = getParameterMap();
76 String[] values = parameterMap.get(name);
77 return values;
78 }
79
80 }
  • To write CharacterEnodingFilter
 1 package com.oracle.bookshop.filter;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12
13 public class CharacterEnodingFilter implements Filter{
14
15 @Override
16 public void destroy() {
17 // TODO Auto-generated method stub
18
19 }
20
21 @Override
22 public void doFilter(ServletRequest request, ServletResponse response,
23 FilterChain chain) throws IOException, ServletException {
24 // TODO Auto-generated method stub
25 HttpServletRequest req = (HttpServletRequest)request;
26 MyHttpServletRequest myreq = new MyHttpServletRequest(req);
27 chain.doFilter(myreq, response);
28
29 }
30
31 @Override
32 public void init(FilterConfig arg0) throws ServletException {
33 // TODO Auto-generated method stub
34
35 }
36
37
38 }

Servlet And Filter More related articles in detail

  1. Android webservice The usage of is explained in detail

    Android webservice The usage of is explained in detail See a lot of friends to WebService Not really , Let's talk about it in detail WebService, Try to be clear . The project that this article adopts is my graduation project webserv ...

  2. servlet Of filter Use

    One . summary The filters are servlet An important feature of , It provides a mechanism , Allow in the filter , That is, you can modify the request information of the browser , You can also modify the response information processed by the server . A filter is an implementation of Filter Interface java class ...

  3. Servlet and Filter Of url Match and url-pattern Detailed explanation And filter The solution to the circulation problem

    Servlet and filter yes J2EE Common technologies in development , Easy to use , Simple configuration , For young and old . It is estimated that most of my friends are directly configured with , I didn't care about the details , There is a problem today , I checked it on the Internet servlet It's just found out that ,ser ...

  4. introduce of servlet and filter

    servlet brief introduction : Java Servlet Is running on the Web A program on a server or application server , It's as coming from Web Browser or something HTTP Client requests and HTTP Between databases or applications on the server ...

  5. Java Servlet (1) —— Filter Filtering requests and responses

    Java Servlet (1) -- Filter Filtering requests and responses edition : Java EE 6 Reference source : Oracle:The Java EE 6 Tutorial: Filtering Reque ...

  6. servlet,listener,filter,interceptor The relationship between

    1.servlet:servlet It's a kind of running on the server side java Applications , Platform - and protocol-independent , And can dynamically generate web page , It works in the middle layer between client request and server response . The earliest support Servlet technology ...

  7. Siki_Unity_2-1_API Common methods and classes are explained in detail ( Next )

    Unity 2-1 API Common methods and classes are explained in detail ( Next ) Mission 101&102: Radiographic testing ray origin + direction: Radiographic testing : Does the ray collide with an object ( Objects need colliders ), Information about colliding objects ...

  8. Servlet and Filter Of url Match and url-pattern Detailed explanation

    Servlet and filter yes J2EE Common technologies in development , Easy to use , Simple configuration , For young and old . It is estimated that most of my friends are directly configured with , I didn't care about the details , There is a problem today , I checked it on the Internet servlet It's just found out that ,ser ...

  9. Iframe A detailed explanation of usage

    1 from :https://blog.csdn.net/judyge/article/details/51786064 zIframe  A detailed explanation of usage hold iframe Interpreted as “ Browser in browser “ Very appropriate & ...

Random recommendation

  1. FreeMarker Label Introduction

    from :http://www.blogjava.net/kxbin/articles/366505.html FreeMarker Label use   One .FreeMarker Template files mainly include 4 Component composition   1. Text ...

  2. use Xshell visit In the virtual machine kali

    1.vim /etc/ssh/sshd_config 2.PermitRootLogin without-password Copy 3. Put one PermitRootLogin without-passwor ...

  3. LFS, Compile your own Linux System - Finish the preparations

    $LFS Make sure that the environment variables $LFS Has been defined . Definition :export LFS=/mnt/lfs Check :echo $LFS Build directory $LFS/tools $LFS/tools Directory is used to store and compile some temporary tools ...

  4. 【cocos2dx-3.0beta- Make flappybird】 Follow the trend of the times , About engine upgrades

    cocos2dx3.1 The version number will be released , Originally , I want to upgrade this to the official 3.0 Version number . Just helpless 3.0 The official version of the pit won't do it , Even frame animation is the right and timely issue , Give up decisively , With the support of the masses of prostitutes . I've upgraded to the latest code c ...

  5. hud 2099

    #include <stdio.h> #include <stdlib.h> int main() { int m,n,i,flag; ) { flag=; && ...

  6. python Realization : Longest substring

    Given a string s And positive integers n, Please use your familiar programming language to output s Contains no more than n The longest substring of two characters , Such as s="uabbcadbaef",n=4 Should output "abbca ...

  7. Foreach usage

    Loop statement is the basic statement of programming , stay C# In addition to using C Out of the loop of language , It also provides foreach Statement to implement the loop . So what I'm going to say is , Try to use... In cycle operation foreach Statement to implement .   In order to better explain why we should advocate ...

  8. Java Learning notes 49(DBUtils Tool class II )

    The last article was our own simulation DBUtils Tool class , In fact, there are well developed tools Use here commons-dbutils-1.6.jar A brief introduction to the transaction : Applying transaction cases in databases : Transfer case Zhang San and Li Si have their own opinions ...

  9. Stanford CS231n Practice notes ( Class hour 14 Convolution neural network On )

    In this lesson, we mainly study a " Convolutional neural networks in browsers " It's just a show project , But it helps to see things intuitively Address :https://cs.stanford.edu/people/karpa ...

  10. Redis Source code reading ( One ) Event mechanism

    Redis Source code reading ( One ) Event mechanism Redis As a NoSQL Non relational memory database , It has high read-write performance , And the native data types are rich , Widely used as a cache . Distributed database . Message queuing and other applications . Besides Redis There's a lot more to come ...