Java filter中的chain.doFilter使用詳解

filter中的chain.doFilter使用

chain.doFilter作用

1.一般filter都是一個鏈,web.xml 裡面配置瞭幾個就有幾個。一個一個的連在一起

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

2.chain.doFilter將請求轉發給過濾器鏈下一個filter , 如果沒有filter那就是你請求的資源

舉例說明

1.input.jsp 是用來提交輸入的 : 當提交後,過濾器檢測姓名和年齡 .

2.如果正常的話會提交給output.jsp 如果不正常提交給erroroutput.jsp.

3.在此 , 同時也有一個過濾器,防止亂碼問題存在 , 該過濾器檢測一個頁面是否設置瞭字符編碼,如果沒有則進行設置。

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);//到下一個鏈
    }
    public void init(FilterConfig fConfig) throws ServletException {
        this.config=fConfig;
        encoding=fConfig.getInitParameter("encoding");//獲得目標編碼格式
    }
}

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,"用戶名和年齡輸入錯誤!");
            dispatch.forward(request, response);
            return;
        }
        else{
            try {
                age1=Integer.parseInt(age);
            }catch(Exception e){
                //JOptionPane.showMessageDialog(null,"年齡必須為數字!");
                dispatch.forward(request,response);
                return;//如果是錯誤頁面就到erroroutput.jsp中
            }
        }
        //這裡表示是正確的,也就是說,他回去找下一個鏈,但是它下面已經沒有瞭,所以就會去跳轉頁面瞭,此跳轉的頁面就是action="output.jsp"瞭
        chain.doFilter(request, response);
        }
}

Filter中chain.doFilter(req, res)的理解

在寫代碼中,每次看到Filter(過濾器)中 chain.doFilter(req, res);都不懂為什麼要加這一句,他的作用是什麼;

代碼下面也有:

@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();
  //不懂這句什麼意思  
  chain.doFilter(req, res);  
  long endTime = System.currentTimeMillis();
  try {
   int status = res.getStatus();
   String charset=res.getCharacterEncoding();
   //響應體
   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();
  }
 }

用法

在doFilter()方法中,在chain.doFilter()之前的代碼,一般是對request執行的過濾操作;

在chain.doFilter()後面的代碼,一般是對response執行的操作;

chain.doFiter()執行下一個過濾器或者業務處理器。

如果在doFilter()方法中,不寫chain.doFilter(),業務無法繼續往下處理;

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: