Example of java servlet filter

Time:2020-11-27

Introduction to servlet filter     
Servlet filter is actually a standard Java class. This class obtains the function of filter by implementing the filter interface. It passes through the JSP container when it starts web.xml The configuration file is loaded by the system.
The servlet filter is called when receiving the user’s request. When the server receives the user’s request, it calls the configured filter in turn. After the completion, the servlet required by the request will be executed. The response of the servlet after execution is sent to the user through the configured filter.

Purpose of the filter:
1. User authentication and authorization management.
2. Statistics of web application visits and hit rate, generate access reports.
3. Realize the log processing function of web application.
4. The function of data compression is realized.
5. Encrypt the transmitted data.
6. Realize the transformation of XML file’s XSLT.
A servlet filter is actually a Java class. Its implementation needs to be divided into two parts: the Java class itself and the web.xml The XML description in the file. For the filter interface, the interface is described by a pair of life cycle methods init(), destroy(), the init method will be called when the server initializes the filter, and the destroy method will be called when the server is shut down. There is also a behavior method called dofilter method when performing the filtering operation

Configuration of servlet filter
The server filter needs to deploy the descriptor file through the web application web.xml To deploy to the application. The configuration is as follows

Copy codeThe code is as follows:
< filter>
    <filter-name>Filtername</filter-name>

    <filter-class>com.filter.Filter/class</filter-class>

       <init-param>
   <param-name>file</param-name>
   <param-value>filename</param-value>
       </init-param>
    </filter>

    <filter-mapping>
 <filter-name>Filtername</filter-name>
<url-pattern>/*</url-pattern>
   </filter-mapping>

Here is an example:

Use filter to solve the problem of Chinese coding
Since the default encoding method of Java is iso-8859-1, the Chinese applications are usually written in GB2312 or GBK. In this case, the encoding of the page should be specified at the beginning of the page through the <% @ page contenttype = “text / HTML; charset = GBK”% > command. In this way, the Chinese page can be displayed normally. But if the page is Murakami form. For example, in an input box, if a visitor enters Chinese in it and submits it to a servlet for processing, Java will first encode the text according to the default method of iso-5589-1, and then send it to serve for processing. The processed text will still be encoded in iso-5589-1 mode. If this text is returned to a page displayed in GBK code, the Different from the encoding format, it is obvious that the correct display results can not be obtained.
There are many ways to solve the coding problem. Here, we mainly introduce the filter to solve the problem of Chinese coding

Copy codeThe code is as follows:
public class CharacterEncodingFilter implements Filter {
private FilterConfig config;
private String encoding = “ISO8859_1”;
public void destroy() {

  config = null;

}

public void doFilter(ServletRequest request, ServletResponse response ,

   FilterChain chain) throws IOException, ServletException {

  request.setCharacterEncoding(encoding);

  chain.doFilter(request, response);

}

public void init(FilterConfig config) throws ServletException {

  this.config  = config;

  String s = config.getInitParameter(“encoding”);

  if(s!=null){

   encoding = s;

  }

}

}

The XML is then configured in:

 

Copy codeThe code is as follows:
 <filter>

    <filter-name>encodingFilter</filter-name>

    <filter-class>com.filter.CharacterEncodingFilter</filter-class>

    <init-param>

      <param-name>encoding</param-name>

      <param-value>utf-8</param-value>

    </init-param>

  </filter>

  <filter-mapping>

    <filter-name>encodingFilter</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>
 

Finally encoding.jsp How to write?

 

Copy codeThe code is as follows:
User name: < C: out value = “${ param.username }” default=”none”></c:out><br>

Password: < C: out value = “${ param.userpassword }” default=”none”></c:out><br>

      <form action=”MyJsp.jsp” method=”post”>

User name: < input type = “test” name = “username” > < br > and

Password: < input type = “password” name = “userpassword” > < br > and

< input type = submit “value = submit” >

      </form>
 

Start Tomcat and visit encoding.jsp After the filter, the page can display the information sent out by the server normally…

Logging user access logs using filters
For some projects, it has to have a detailed record of each user visit. Well, this is a very good solution to use logging, and it is easy to record every user’s access with a filter. Otherwise, the same site will not be able to log in the same time because the server is full. Therefore, the session object can be used to judge each session of the user. In a session, the filter will only record once.
The logfilter class is written below. This filter is mainly responsible for recording the user’s access records:

Copy codeThe code is as follows:
package com.filter;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import java.text.SimpleDateFormat;
import java.util.Date;
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.HttpSession;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class LoginFilter implements Filter{

  private FilterConfig config =null;
  private String filename = null;
  private String filtername = null;
  public void destroy() {
    this.config = null;
    this.filename = null;
    this.filtername = null;
  }

  public void doFilter(ServletRequest request , ServletResponse response,
      FilterChain chain ) throws IOException, ServletException {
    HttpServletRequest hRequest = (HttpServletRequest) request;
/ / get the session object
    HttpSession session = hRequest.getSession();
/ / first, judge whether the logged in the session has a value. If not, it indicates that it is a new request
    if(null==session.getAttribute(“LOGGED”)){
      session.setAttribute (“logged”, “yes”); / / set the value of logged to yes to prevent duplicate recording of the same session
      File file = new File(this.filename);
      if(!file.exists())
        file.createNewFile (); / / judge whether the file exists. If not, create a new one

      /*
* create log content, including the visitor’s IP address, page URL and time of visit, and the name of the log filter
       */
      String logContent = hRequest.getRemoteHost()+”->”+hRequest.getRequestURI()+” Logged “+getTime()+” By s”+this.filtername+”\r\n”;
      RandomAccessFile rf = new RandomAccessFile( this.filename “; / / create a random file operation object
      rf.seek ( rf.length ()); / / points the write pointer to the end of the file, rf.length () gets the length of the file. The length of the seek file is exactly the end of the file
      rf.writeBytes (logcontent); / / write the log to the file
      rf.close (); / / close file
    }
    chain.doFilter(request, response);
  }

  public void init(FilterConfig config) throws ServletException {
    this.config = config;
    this.filename = this.config.getInitParameter(“file”);
    this.filtername = this.config.getFilterName();
  }

/ / get the time
  private String getTime(){
    SimpleDateFormat sdf  = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”);
    return sdf.format(new Date());
  }

}

The session is used to restrict the same session to log only once. However, no matter how many pages visitors visit in this session, during the first visit, because the session’s logged is empty, the log is recorded and set to yes at this time. In this way, the log will not be executed during the second judgment.
Then, configure XML in:

Copy codeThe code is as follows:
<filter>
    <filter-name>LogFilter</filter-name>
    <filter-class>com.filter.LoginFilter</filter-class>
    <init-param>
      <param-name>file</param-name>
      <param-value>D:/log.txt</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>LogFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

After the XML is configured, you can access any file in the following directory in the D:/ log.txt Get a record of the visitors in the file.

Recommended Today

Regular expression sharing for checking primes

This regular expression is shown as follows: Regular expressions for checking prime numbers or not To use this positive regular expression, you need to convert the natural number into multiple 1 strings. For example, 2 should be written as “11”, 3 should be written as “111”, 17 should be written as “11111111111”. This kind of […]