A common use of Filter of filters in javaweb

  • 2020-04-01 04:32:05
  • OfStack

1. Unified character encoding of the whole station

The charset configuration parameter indicates which character encoding to use to handle the Chinese language of Html Form request parameters


package me.gacl.web.filter;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

 
public class CharacterEncodingFilter implements Filter {

  private FilterConfig filterConfig = null;
  //Set the default character encoding
  private String defaultCharset = "UTF-8";

  public void doFilter(ServletRequest req, ServletResponse resp,
      FilterChain chain) throws IOException, ServletException {
    
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    String charset = filterConfig.getInitParameter("charset");
    if(charset==null){
      charset = defaultCharset;
    }
    request.setCharacterEncoding(charset);
    response.setCharacterEncoding(charset);
    response.setContentType("text/html;charset="+charset);
    
    MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request);
    chain.doFilter(requestWrapper, response);
  }

  public void init(FilterConfig filterConfig) throws ServletException {
    //Gets the initialization configuration information for the filter
    this.filterConfig = filterConfig;
  }
  
  public void destroy() {

  }
}


 
class MyCharacterEncodingRequest extends HttpServletRequestWrapper{
  
  private HttpServletRequest request;
  public MyCharacterEncodingRequest(HttpServletRequest request) {
    super(request);
    this.request = request;
  }
  
  @Override
  public String getParameter(String name) {
    
    try{
      //Gets the value of the parameter
      String value= this.request.getParameter(name);
      if(value==null){
        return null;
      }
      //If the data is not submitted by get, the retrieved value is returned directly
      if(!this.request.getMethod().equalsIgnoreCase("get")) {
        return value;
      }else{
        //If the data is submitted by get, the obtained value is transcoded
        value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding());
        return value;
      }
    }catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

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


<filter>
   <filter-name>CharacterEncodingFilter</filter-name>
   <filter-class>me.gacl.web.filter.CharacterEncodingFilter</filter-class>
   <init-param>
     <param-name>charset</param-name>
     <param-value>UTF-8</param-value>
   </init-param>
 </filter>
 
 <filter-mapping>
   <filter-name>CharacterEncodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

The browser is not allowed to cache all dynamic pages
There are three HTTP response header fields that all prohibit the browser from caching the current page, and their sample code in the Servlet is as follows:

The response. SetDateHeader (" Expires ", 1); Response. SetHeader (" cache-control ", "no - Cache"); The response. SetHeader (" Pragma ", "no - cache");

Not all browsers fully support the three response headers above, so it is best to use all three at once.

Expires header: the value is GMT time value and -1 means that the browser does not cache the page The cache-control response header has two common values: No-cache means that the browser does not cache the current page. Max-age: XXX means the browser cache page in XXX seconds.


package me.gacl.web.filter;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 
public class NoCacheFilter implements Filter {


  public void doFilter(ServletRequest req, ServletResponse resp,
      FilterChain chain) throws IOException, ServletException {
    //Strong ServletRequest to HttpServletRequest
    HttpServletRequest request = (HttpServletRequest) req;
    //Strongly convert the ServletResponse to HttpServletResponse
    HttpServletResponse response = (HttpServletResponse) resp;
    //Browsers are not allowed to cache all dynamic pages
    response.setDateHeader("Expires", -1);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    
    chain.doFilter(request, response);
  }

  public void init(FilterConfig filterConfig) throws ServletException {

  }
  
  public void destroy() {
    
  }
}

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


<filter>
   <filter-name>NoCacheFilter</filter-name>
   <filter-class>me.gacl.web.filter.NoCacheFilter</filter-class>
 </filter>
 
 <filter-mapping>
   <filter-name>NoCacheFilter</filter-name>
    <!-- Only to intercept Jsp request -->
   <servlet-name>*.jsp</servlet-name>
 </filter-mapping>

Third, control the browser cache page in the static resources

Some dynamic pages refer to images or CSS files to decorate the page effect. These images and CSS files are often unchanged, so to reduce the pressure on the server, you can use filters to control the browser cache of these files to improve the performance of the server.


package me.gacl.web.filter;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 
public class CacheFilter implements Filter {

  private FilterConfig filterConfig;

  public void doFilter(ServletRequest req, ServletResponse resp,
      FilterChain chain) throws IOException, ServletException {
  
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    
    //1. Get the resources the user wants to access
    String uri = request.getRequestURI(); 
    
    //2. Get the suffix name of the resource the user wants to access
    String ext = uri.substring(uri.lastIndexOf(".")+1);
    
    //The time it takes to cache the resource
    String time = filterConfig.getInitParameter(ext);
    if(time!=null){
      long t = Long.parseLong(time)*3600*1000;
      //Set the cache
      response.setDateHeader("expires", System.currentTimeMillis() + t);
    }
    
    chain.doFilter(request, response);

  }

  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
  }
  
  public void destroy() {
    
  }
}

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


<!--  Configure the cache filter  -->
  <filter>
   <filter-name>CacheFilter</filter-name>
   <filter-class>me.gacl.web.filter.CacheFilter</filter-class>
    <!--  Configure which to cache web Resources and cache time in hours  -->
   <init-param>
     <param-name>css</param-name>
     <param-value>4</param-value>
   </init-param>
   <init-param>
     <param-name>jpg</param-name>
     <param-value>1</param-value>
   </init-param>
   <init-param>
     <param-name>js</param-name>
     <param-value>4</param-value>
   </init-param>
   <init-param>
     <param-name>png</param-name>
     <param-value>4</param-value>
   </init-param>
 </filter>
 <!--  Configure which to cache web Suffix of resource -->
 <filter-mapping>
   <filter-name>CacheFilter</filter-name>
   <url-pattern>*.jpg</url-pattern>
 </filter-mapping>
 
 <filter-mapping>
   <filter-name>CacheFilter</filter-name>
   <url-pattern>*.css</url-pattern>
 </filter-mapping>
 
 <filter-mapping>
   <filter-name>CacheFilter</filter-name>
   <url-pattern>*.js</url-pattern>
 </filter-mapping>
  <filter-mapping>
   <filter-name>CacheFilter</filter-name>
   <url-pattern>*.png</url-pattern>
 </filter-mapping>

Four, the realization of users automatically login

The idea is this:

1. After the user successfully logs in, send a cookie named user to the client. The value of the cookie is the user name and the password encrypted by md5.
2. Write an AutoLoginFilter, which checks whether the user has a cookie with the name of user. If so, call dao to inquire whether the username and password of the cookie match the database.

The core code is as follows:

The controller that handles user login: LoginServlet


package me.gacl.web.controller;

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 me.gacl.dao.UserDao;
import me.gacl.domain.User;
import me.gacl.util.WebUtils;

public class LoginServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    
    UserDao dao = new UserDao();
    User user = dao.find(username, password);
    if(user==null){
      request.setAttribute("message", " Wrong username or password!! ");
      request.getRequestDispatcher("/message.jsp").forward(request, response);
      return;
    }
    request.getSession().setAttribute("user", user);
    //Send an automatic login cookie to the client browser for storage
    sendAutoLoginCookie(request,response,user);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
  }

   
  private void sendAutoLoginCookie(HttpServletRequest request, HttpServletResponse response, User user) {
    if (request.getParameter("logintime")!=null) {
      int logintime = Integer.parseInt(request.getParameter("logintime"));
      //Create cookie, the name of cookie is autologin, the value is the user login username and password, the user name and password used between
      Cookie cookie = new Cookie("autologin",user.getUsername() + "." + WebUtils.md5(user.getPassword()));
      //Set the expiry date of the cookie
      cookie.setMaxAge(logintime);
      //Sets a valid path to the cookie
      cookie.setPath(request.getContextPath());
      //Writes the cookie to the client browser
      response.addCookie(cookie);
    }
  }
  
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    doGet(request, response);
  }

}

The filter that handles automatic user login: AutoLoginFilter


package me.gacl.web.filter;

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.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.gacl.dao.UserDao;
import me.gacl.domain.User;
import me.gacl.util.WebUtils;

public class AutoLoginFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse resp,
      FilterChain chain) throws IOException, ServletException {
    
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    //If you are already logged in, direct chain-dofilter (request, response) releases
    if(request.getSession().getAttribute("user")!=null){
      chain.doFilter(request, response);
      return;
    }
    
    //1. Get the cookie of authlogin brought by the user
    String value = null;
    Cookie cookies[] = request.getCookies();
    for(int i=0;cookies!=null && i<cookies.length;i++){
      if(cookies[i].getName().equals("autologin")){
        value = cookies[i].getValue();
      }
    }
    
    //2. Get the username and password in the cookie
    if(value!=null){
      String username = value.split("\.")[0];
      String password = value.split("\.")[1];
      
      //3. Call dao to get the user's password
      UserDao dao = new UserDao();
      User user = dao.find(username);
      String dbpassword = user.getPassword();
      
      //4. Check whether the password of md5 brought by the user matches the password in the database. If it matches, the user will log in automatically
      if(password.equals(WebUtils.md5(dbpassword))){
        request.getSession().setAttribute("user", user);
      }
    }
    
    chain.doFilter(request, response);
  }
  
  public void destroy() {
    
  }

  public void init(FilterConfig filterConfig) throws ServletException {

  }
}

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


package me.gacl.web.controller;

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;

public class CancelAutoLoginServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    //Removes the user stored in session
    request.getSession().removeAttribute("user");
    //Remove the automatically logged in cookie
    removeAutoLoginCookie(request,response);
    //Log out the user and jump to the login page
    request.getRequestDispatcher("/login.jsp").forward(request, response);
  }

   
  private void removeAutoLoginCookie(HttpServletRequest request, HttpServletResponse response) {
    //Create a cookie with the name autologin
    Cookie cookie = new Cookie("autologin","");
     //Set the expiry date of the cookie to 0, and command the browser to delete the cookie
    cookie.setMaxAge(0);
    //Set the path of the cookie to delete
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);
  }
  
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

Above is the filter of a few common application scenarios, hope to help you learn.


Related articles: