One 、 Unified station character coding

By configuring the parameters charset Indicates which character encoding to use , To deal with Html Form Request parameters in Chinese

 1 package me.gacl.web.filter;
2
3 import java.io.IOException;
4 import javax.servlet.Filter;
5 import javax.servlet.FilterChain;
6 import javax.servlet.FilterConfig;
7 import javax.servlet.ServletException;
8 import javax.servlet.ServletRequest;
9 import javax.servlet.ServletResponse;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletRequestWrapper;
12 import javax.servlet.http.HttpServletResponse;
13
14 /**
15 * @ClassName: CharacterEncodingFilter
16 * @Description: This filter is used to solve the problem of garbled Chinese in the whole station
17 * @author: The lone wolf
18 * @date: 2014-8-31 Afternoon 11:09:37
19 *
20 */
21 public class CharacterEncodingFilter implements Filter {
22
23 private FilterConfig filterConfig = null;
24 // Set the default character encoding
25 private String defaultCharset = "UTF-8";
26
27 public void doFilter(ServletRequest req, ServletResponse resp,
28 FilterChain chain) throws IOException, ServletException {
29
30 HttpServletRequest request = (HttpServletRequest) req;
31 HttpServletResponse response = (HttpServletResponse) resp;
32 String charset = filterConfig.getInitParameter("charset");
33 if(charset==null){
34 charset = defaultCharset;
35 }
36 request.setCharacterEncoding(charset);
37 response.setCharacterEncoding(charset);
38 response.setContentType("text/html;charset="+charset);
39
40 MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request);
41 chain.doFilter(requestWrapper, response);
42 }
43
44 public void init(FilterConfig filterConfig) throws ServletException {
45 // Get the initialization configuration information of the filter
46 this.filterConfig = filterConfig;
47 }
48
49 public void destroy() {
50
51 }
52 }
53
54 /*
55 1. Implement the same interface as the enhanced object
56 2、 Define a variable to remember the enhanced object
57 3、 Define a constructor , Receiving enhanced objects
58 4、 Coverage needs to be enhanced
59 5、 For methods that don't want to be enhanced , Call the enhanced object directly ( Target audience ) Methods
60 */
61
62 class MyCharacterEncodingRequest extends HttpServletRequestWrapper{
63
64 private HttpServletRequest request;
65 public MyCharacterEncodingRequest(HttpServletRequest request) {
66 super(request);
67 this.request = request;
68 }
69 /* rewrite getParameter Method
70 * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
71 */
72 @Override
73 public String getParameter(String name) {
74
75 try{
76 // Get the value of the parameter
77 String value= this.request.getParameter(name);
78 if(value==null){
79 return null;
80 }
81 // If not by get How to submit data , It directly returns the obtained value
82 if(!this.request.getMethod().equalsIgnoreCase("get")) {
83 return value;
84 }else{
85 // If so get How to submit data , Transcoding the obtained value
86 value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding());
87 return value;
88 }
89 }catch (Exception e) {
90 throw new RuntimeException(e);
91 }
92 }
93 }

web.xml The configuration in the file is as follows :

 1 <filter>
2 <filter-name>CharacterEncodingFilter</filter-name>
3 <filter-class>me.gacl.web.filter.CharacterEncodingFilter</filter-class>
4 <init-param>
5 <param-name>charset</param-name>
6 <param-value>UTF-8</param-value>
7 </init-param>
8 </filter>
9
10 <filter-mapping>
11 <filter-name>CharacterEncodingFilter</filter-name>
12 <url-pattern>/*</url-pattern>
13 </filter-mapping>

Two 、 Prevent browsers from caching all dynamic pages

Yes 3 individual HTTP The response header field can disable the browser from caching the current page , They are Servlet The sample code in is as follows :

1 response.setDateHeader("Expires",-1);
2 response.setHeader("Cache-Control","no-cache");
3 response.setHeader("Pragma","no-cache");

None of the top three browsers are fully responsive , So it's best to use the three response headers above at the same time .

  • Expires Data header : The value is GMT Time value , by -1 The browser does not cache pages
  • Cache-Control The response header has two common values :
  • no-cache Do not cache the current page .
  • max-age:xxx Refers to the browser cache page xxx second .
 1 package me.gacl.web.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 import javax.servlet.http.HttpServletResponse;
13
14 /**
15 * @ClassName: NoCacheFilter
16 * @Description: Prevent browsers from caching all dynamic pages
17 * @author: The lone wolf
18 * @date: 2014-8-31 Afternoon 11:25:40
19 *
20 */
21 public class NoCacheFilter implements Filter {
22
23
24 public void doFilter(ServletRequest req, ServletResponse resp,
25 FilterChain chain) throws IOException, ServletException {
26 // hold ServletRequest Strong conversion HttpServletRequest
27 HttpServletRequest request = (HttpServletRequest) req;
28 // hold ServletResponse Strong conversion HttpServletResponse
29 HttpServletResponse response = (HttpServletResponse) resp;
30 // Prevent browsers from caching all dynamic pages
31 response.setDateHeader("Expires", -1);
32 response.setHeader("Cache-Control", "no-cache");
33 response.setHeader("Pragma", "no-cache");
34
35 chain.doFilter(request, response);
36 }
37
38 public void init(FilterConfig filterConfig) throws ServletException {
39
40 }
41
42 public void destroy() {
43
44 }
45 }

web.xml The configuration in the file is as follows :

 1 <filter>
2 <filter-name>NoCacheFilter</filter-name>
3 <filter-class>me.gacl.web.filter.NoCacheFilter</filter-class>
4 </filter>
5
6 <filter-mapping>
7 <filter-name>NoCacheFilter</filter-name>
8 <!-- Intercept only Jsp request -->
9 <servlet-name>*.jsp</servlet-name>
10 </filter-mapping>

3、 ... and 、 Control the static resources in the browser cache page

Some dynamic pages refer to some pictures or css To embellish a page with a file effect , These pictures and css Documents are often unchangeable , So in order to reduce the pressure on the server , have access to filter Control the browser to cache these files , To improve the performance of the server .

 1 package me.gacl.web.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 import javax.servlet.http.HttpServletResponse;
13
14 /**
15 * @ClassName: CacheFilter
16 * @Description: Control cached filter
17 * @author: The lone wolf
18 * @date: 2014-9-1 Afternoon 9:39:38
19 *
20 */
21 public class CacheFilter implements Filter {
22
23 private FilterConfig filterConfig;
24
25 public void doFilter(ServletRequest req, ServletResponse resp,
26 FilterChain chain) throws IOException, ServletException {
27
28 HttpServletRequest request = (HttpServletRequest) req;
29 HttpServletResponse response = (HttpServletResponse) resp;
30
31 //1. Get the resources users want to access
32 String uri = request.getRequestURI();
33
34 //2. Get the suffix of the resource the user wants to access
35 String ext = uri.substring(uri.lastIndexOf(".")+1);
36
37 // Get the time that the resource needs to be cached
38 String time = filterConfig.getInitParameter(ext);
39 if(time!=null){
40 long t = Long.parseLong(time)*3600*1000;
41 // Set the cache
42 response.setDateHeader("expires", System.currentTimeMillis() + t);
43 }
44
45 chain.doFilter(request, response);
46
47 }
48
49 public void init(FilterConfig filterConfig) throws ServletException {
50 this.filterConfig = filterConfig;
51 }
52
53 public void destroy() {
54
55 }
56 }

web.xml The configuration in the file is as follows :

 1 <!-- Configure cache filters -->
2 <filter>
3 <filter-name>CacheFilter</filter-name>
4 <filter-class>me.gacl.web.filter.CacheFilter</filter-class>
5 <!-- Configure the web Resources and cache time , In hours -->
6 <init-param>
7 <param-name>css</param-name>
8 <param-value>4</param-value>
9 </init-param>
10 <init-param>
11 <param-name>jpg</param-name>
12 <param-value>1</param-value>
13 </init-param>
14 <init-param>
15 <param-name>js</param-name>
16 <param-value>4</param-value>
17 </init-param>
18 <init-param>
19 <param-name>png</param-name>
20 <param-value>4</param-value>
21 </init-param>
22 </filter>
23 <!-- Configure the web The suffix of the resource -->
24 <filter-mapping>
25 <filter-name>CacheFilter</filter-name>
26 <url-pattern>*.jpg</url-pattern>
27 </filter-mapping>
28
29 <filter-mapping>
30 <filter-name>CacheFilter</filter-name>
31 <url-pattern>*.css</url-pattern>
32 </filter-mapping>
33
34 <filter-mapping>
35 <filter-name>CacheFilter</filter-name>
36 <url-pattern>*.js</url-pattern>
37 </filter-mapping>
38 <filter-mapping>
39 <filter-name>CacheFilter</filter-name>
40 <url-pattern>*.png</url-pattern>
41 </filter-mapping>

Four 、 Realize the automatic login of users

This is the idea :

1、 After the user login successfully , Send a message named user Of cookie To the client ,cookie The values of are user name and md5 Encrypted password .
2、 Write a AutoLoginFilter, This filter Check that the user has the name user Of cookie Come on , If there is , Call dao Inquire about cookie Whether the user name and password of match the database , Matching is to session Deposit in user object ( That is, the user login flag ), In order to realize the program to complete automatic login .

The core code is as follows :

The controller that handles user login :LoginServlet

 1 package me.gacl.web.controller;
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
11 import me.gacl.dao.UserDao;
12 import me.gacl.domain.User;
13 import me.gacl.util.WebUtils;
14
15 public class LoginServlet extends HttpServlet {
16
17 public void doGet(HttpServletRequest request, HttpServletResponse response)
18 throws ServletException, IOException {
19
20 String username = request.getParameter("username");
21 String password = request.getParameter("password");
22
23 UserDao dao = new UserDao();
24 User user = dao.find(username, password);
25 if(user==null){
26 request.setAttribute("message", " Wrong user name or password !!");
27 request.getRequestDispatcher("/message.jsp").forward(request, response);
28 return;
29 }
30 request.getSession().setAttribute("user", user);
31 // Send automatic login cookie Store for client browser
32 sendAutoLoginCookie(request,response,user);
33 request.getRequestDispatcher("/index.jsp").forward(request, response);
34 }
35
36 /**
37 * @Method: sendAutoLoginCookie
38 * @Description: Send automatic login cookie To the client browser
39 * @Anthor: The lone wolf
40 *
41 * @param request
42 * @param response
43 * @param user
44 */
45 private void sendAutoLoginCookie(HttpServletRequest request, HttpServletResponse response, User user) {
46 if (request.getParameter("logintime")!=null) {
47 int logintime = Integer.parseInt(request.getParameter("logintime"));
48 // establish cookie,cookie The name of is autologin, The value is the user name and password for the user to log in , Between user name and password . Segmentation , The password goes through md5 Encryption processing
49 Cookie cookie = new Cookie("autologin",user.getUsername() + "." + WebUtils.md5(user.getPassword()));
50 // Set up cookie The validity of the
51 cookie.setMaxAge(logintime);
52 // Set up cookie The effective path
53 cookie.setPath(request.getContextPath());
54 // take cookie Write to the client browser
55 response.addCookie(cookie);
56 }
57 }
58
59 public void doPost(HttpServletRequest request, HttpServletResponse response)
60 throws ServletException, IOException {
61
62 doGet(request, response);
63 }
64
65 }

Filter for handling automatic user login :AutoLoginFilter

 1 package me.gacl.web.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.HttpServletResponse;
14
15 import me.gacl.dao.UserDao;
16 import me.gacl.domain.User;
17 import me.gacl.util.WebUtils;
18
19 public class AutoLoginFilter implements Filter {
20
21 public void doFilter(ServletRequest req, ServletResponse resp,
22 FilterChain chain) throws IOException, ServletException {
23
24 HttpServletRequest request = (HttpServletRequest) req;
25 HttpServletResponse response = (HttpServletResponse) resp;
26 // If you are already logged in , Just directly chain.doFilter(request, response) release
27 if(request.getSession().getAttribute("user")!=null){
28 chain.doFilter(request, response);
29 return;
30 }
31
32 //1. Get it from the user authlogin Of cookie
33 String value = null;
34 Cookie cookies[] = request.getCookies();
35 for(int i=0;cookies!=null && i<cookies.length;i++){
36 if(cookies[i].getName().equals("autologin")){
37 value = cookies[i].getValue();
38 }
39 }
40
41 //2. obtain cookie User name and password in
42 if(value!=null){
43 String username = value.split("\\.")[0];
44 String password = value.split("\\.")[1];
45
46 //3. call dao Get the password of the user
47 UserDao dao = new UserDao();
48 User user = dao.find(username);
49 String dbpassword = user.getPassword();
50
51 //4. Check what the user brings md5 Whether the password of matches the password in the database , If matched, login automatically
52 if(password.equals(WebUtils.md5(dbpassword))){
53 request.getSession().setAttribute("user", user);
54 }
55 }
56
57 chain.doFilter(request, response);
58 }
59
60 public void destroy() {
61
62 }
63
64 public void init(FilterConfig filterConfig) throws ServletException {
65
66 }
67 }

If you want to cancel automatic login , Then you can delete the automatic login when the user logs off cookie, The core code is as follows :

 1 package me.gacl.web.controller;
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
11 public class CancelAutoLoginServlet extends HttpServlet {
12
13 public void doGet(HttpServletRequest request, HttpServletResponse response)
14 throws ServletException, IOException {
15 // Remove stored in session Medium user
16 request.getSession().removeAttribute("user");
17 // Remove automatic login cookie
18 removeAutoLoginCookie(request,response);
19 // Log off the user and jump to the login page
20 request.getRequestDispatcher("/login.jsp").forward(request, response);
21 }
22
23 /**
24 * @Method: removeAutoLoginCookie
25 * @Description: Remove automatic login cookie,
26 * JavaWeb Delete in cookie The way to do that is to create a new cookie, The newly created cookie And to delete cookie The same name ,
27 * Set the newly created cookie Of cookie The validity period of is set to 0, The valid path is the same as the cookie The effective paths are the same
28 * @Anthor: The lone wolf
29 *
30 * @param request
31 * @param response
32 */
33 private void removeAutoLoginCookie(HttpServletRequest request, HttpServletResponse response) {
34 // Create a name for autologin Of cookie
35 Cookie cookie = new Cookie("autologin","");
36 // take cookie The validity period of is set to 0, Command the browser to delete the cookie
37 cookie.setMaxAge(0);
38 // Set the cookie Of path
39 cookie.setPath(request.getContextPath());
40 response.addCookie(cookie);
41 }
42
43 public void doPost(HttpServletRequest request, HttpServletResponse response)
44 throws ServletException, IOException {
45 doGet(request, response);
46 }
47 }

The above are several common application scenarios of filters .

JavaWeb Study ( Twenty-four )————Filter( filter ) More articles about common applications

  1. javaweb Learning summary ( forty-six )——Filter( filter ) Common applications

    One . Unified station character coding By configuring the parameters charset Indicates which character encoding to use , To deal with Html Form Request parameters in Chinese 1 package me.gacl.web.filter; 2 3 import ja ...

  2. Filter Study ( 3、 ... and )Filter( filter ) Common applications

    One . Unified station character coding By configuring the parameters charset Indicates which character encoding to use , To deal with Html Form Request parameters in Chinese : package com.web.filter; import java.io.IOE ...

  3. Python3.5 Learning 24

    The syllabus of this section : -------------------------------------------------------------------------------------------- ...

  4. JavaWeb Study ( Twenty-eight )———— File upload and download

    stay Web Application system development , File upload and download are very common functions , Today, let's talk about JavaWeb File upload and download function in . For file upload , In the process of uploading, the browser submits the file to the server in the form of stream , If used directly ...

  5. JavaWeb Study ( hexacosa- )———— Monitor (Listener) Study ( Two )

    One . A listener that listens for changes in properties in domain objects The event listener for property changes in domain objects is used to listen ServletContext, HttpSession, HttpServletRequest The attribute change letters in these three objects ...

  6. JavaWeb Study ( twenty-five )———— Monitor (Listener)

    One . About the monitor 1.1. The concept of a listener

  7. JavaWeb Study ( twenty )————JavaWeb Two kinds of development mode of the Internet

    One .JSP+JavaBean Development mode 1.1.jsp+javabean Development model architecture jsp+javabean The architecture of the development mode is shown in the figure below ( chart 1-1) Shown

  8. javaweb Learning summary ( fourteen )——JSP principle

    One . What is? JSP? JSP The full name is Java Server Pages, It and servle The technology is the same , All are SUN A company defined one that is used to develop dynamic web Technology of resources . JSP The biggest feature of this technology is , Write jsp It's like writing h ...

  9. javaweb Learning summary 14 (xml It's a constraint Schema)

    One :schema A brief introduction to constraints 1:xml Schema Definition, advantages and disadvantages 2:xml schema introduction 3: Namespace here http://www.itcast.cn It doesn't make any sense , It's just a name . ...

Random recommendation

  1. Why can an anonymous inner class only access final Type of local variable ?

    Most of the time , Class is defined as a separate program unit . In some cases , It also puts one class in the internal definition of another class , Classes defined within other classes are called inner classes , Classes that contain inner classes are also called outer classes . class Outer { priv ...

  2. DWRUtil is not defined

    error :DWRUtil is not defined; resolvent : First check whether the page is correctly introduced uitl.js <script type="text/javascript" src ...

  3. post(c),get(r),put(u),delete(d)

    http://whui0110.iteye.com/blog/1682388 Look at this post, we know that people often say idempotent means repeated execution , The result is the same : Said in the post put(update) Idempotent , Actually update v ...

  4. 【 Technology sharing 】BurpSuite Tips for proxy settings

    author : Think twice Estimated contribution :300RMB Submission method : Send an email to linwei#360.cn, Or go to the web page to contribute online stay Web During penetration testing ,BurpSuite It is one of the indispensable artifact .BurpSuite The core is ...

  5. 【LeetCode One question a day 】Add Binary( Binary addition )

    Given two binary strings, return their sum (also a binary string).The input strings are both non-emp ...

  6. establish iview Projects of the framework

    http://www.cnblogs.com/jf-67/p/8479176.html In the use of ‘vue init webpack my-project’ When you create a project , There was a mistake npm ERR! cod ...

  7. Java Program flow control : Judging structure 、 Selection structure 、 Loop structure

    The content of this article is : Judging structure if Selection structure switch Loop structure while do-while for for each break.continue return Starting time :2017-06-22 21: ...

  8. HDU 6406 Taotao Picks Apples Line tree maintenance

    The question : Give me one T,T Group data : One for each group n,m:n Number ,m Operations : ( The operation on the sequence is , Let's start by assuming that what you have is -INF, To i=1 Pick up when 1, And then go through , Replace when you have a larger quantity than you have on hand ( Take what you have ), Ask and finally take ...

  9. python salt Realization windows Account automation

    import random import string import json import logging import time import os import sys def usage(): ...

  10. Linux Fundamentals of entry ( Two ):Linux Disk and file management system

    Disk management fdisk Partitioning tool Only support MBR Partition fdisk The order is just root The user can use fdisk -l List all installation disks and partition information fdisk /dev/sda ( Operating disks , Press m Help interface can be listed , Common exercises ...