Detailed explanation of chain. doFilter in Java filter

  • 2021-12-13 07:53:29
  • OfStack

chain. doFilter in the directory filter uses chain. doFilter as an example to illustrate the understanding and usage of chain. doFilter (req, res) in Filter

Use of chain in filter. doFilter

chain. doFilter action

1.1 filter is a chain, and web. xml has several configurations. One by one is connected to one

request - > filter1 - > filter2 - > filter3 - > ...- > request resource.

2. chain. doFilter forwards the request to an filter under the filter chain. If there is no filter, it is the resource you requested

Illustrate with examples

1. input. jsp is used to submit input: When submitted, the filter detects the name and age.

2. Submit to output. jsp if normal. Submit to erroroutput. jsp if not.

3. Here, there is also a filter to prevent garbled problems. The filter detects whether a page is set with character coding, and if not, sets it.

1.input.jsp


<form action="output.jsp" name="form" method="post">
    <table>
        <tr>
            <td>name</td>
            <td><input type="text" name="name" /></td>
        </tr>
        <tr>
            <td>age</td>
            <td><input type="text" name="age"/></td>
        </tr>
        <tr>
            <td><input type="submit" name="ok" value="ok"/></td>
        </tr>
    </table>
</form>

2.web.xml


<filter>
    <description></description>
    <display-name>encodefilter</display-name>
    <filter-name>encodefilter</filter-name>
    <filter-class>servletbean.encodefilter</filter-class>
    <init-param>
           <param-name>encoding</param-name>
           <param-value>GB2312</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodefilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
    <description></description>
    <display-name>myfilter</display-name>
    <filter-name>myfilter</filter-name>
    <filter-class>servletbean.myfilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>myfilter</filter-name>
    <url-pattern>/output.jsp</url-pattern>
</filter-mapping>

3.encodefilter.java


package servletbean;
public class encodefilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(request.getCharacterEncoding()==null) {
            System.out.println(encoding);
            request.setCharacterEncoding(encoding);
        }
        chain.doFilter(request, response);// To the bottom 1 Chain 
    }
    public void init(FilterConfig fConfig) throws ServletException {
        this.config=fConfig;
        encoding=fConfig.getInitParameter("encoding");// Obtain the target encoding format 
    }
}

3.myfilter.java


package servletbean;
import javax.swing.JOptionPane;
public class myfilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setContentType("text/html");
        response.setCharacterEncoding("GB2312");
        PrintWriter out=response.getWriter();
        String name="";
        String age="";
        int age1;
        name=request.getParameter("name");
        age=request.getParameter("age");
        RequestDispatcher dispatch=request.getRequestDispatcher("erroroutput.jsp");
        if(name==null||name==""||name==" "||age==null) {
            JOptionPane.showMessageDialog(null," Incorrect user name and age! ");
            dispatch.forward(request, response);
            return;
        }
        else{
            try {
                age1=Integer.parseInt(age);
            }catch(Exception e){
                //JOptionPane.showMessageDialog(null," Age must be a number! ");
                dispatch.forward(request,response);
                return;// If it is an error page, it will arrive erroroutput.jsp Medium 
            }
        }
        // It's correct here, that is to say, he went back and looked for it 1 A chain, but it is no longer below, so it will jump to the page, and the page that this jump to is action="output.jsp" It's over 
        chain.doFilter(request, response);
        }
}

Understanding of chain. doFilter (req, res) in Filter

In writing code, every time you see chain. doFilter in Filter (filter) (req, res); I don't know why I want to add this sentence and what his role is;

Also below the code:


@Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  ContentCachingRequestWrapper  req=new ContentCachingRequestWrapper((HttpServletRequest) request);
  ContentCachingResponseWrapper res=new ContentCachingResponseWrapper((HttpServletResponse) response);
  long startTime = System.currentTimeMillis();
  String serverUrl = req.getServletPath();
  // I don't know what this sentence means   
  chain.doFilter(req, res);  
  long endTime = System.currentTimeMillis();
  try {
   int status = res.getStatus();
   String charset=res.getCharacterEncoding();
   // Responsive body 
   String responsePayload = getPayLoad(res.getContentAsByteArray(),res.getCharacterEncoding());
   res.copyBodyToResponse();
   if(writeLogService==null) {
    writeLogService = (WriteLogService) ServiceLocator.getInstance().getCtx().getBean("writeLogServiceImpl");
   } 
 writeLogService.writeLog(startTime,endTime,serverUrl,postparams,status,responsePayload,charset);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

Usage

In the doFilter () method, the code before chain. doFilter () is generally a filtering operation performed on request;

The code after chain. doFilter (), 1 is generally the operation performed on response;

chain. doFiter () executes the next filter or service handler.

If chain. doFilter () is not written in the doFilter () method, the business cannot continue processing;


Related articles: