Servlet Filter 可以攔截所有指向服務(wù)端的請求。

如果你想創(chuàng)建一個ServletFilter ,你需要實現(xiàn)一個接口javax.servlet.Filter
import javax.servlet.*;
import java.io.IOException;
public class SimpleServletFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
}
public void destroy() {
}
}
servlet filter 一旦被裝載,首先會調(diào)用它的init()方法。
當(dāng)HTTP請求指向過濾器截獲的服務(wù)端,過濾器可以檢查URI,請求參數(shù)和請求頭,并根據(jù)它決定是否要將請求阻止或轉(zhuǎn)發(fā)到目標(biāo)Servlet,JSP 等
具有攔截功能的方法是doFilter()
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
String myParam = request.getParameter("myParam");
if(!"blockTheRequest".equals(myParam)){
filterChain.doFilter(request, response);
}
}
Notice how the doFilter() method checks a request parameter, myParam, to see if it equals the string "blockTheRequest". If not, the request is forwarded to the target of the request, by calling the filterChain.doFilter() method. If this method is not called, the request is not forwarded, but just blocked.
The servlet filter above just ignores the request if the request parameter myParam equals "blockTheRequest". You can also write a different response back to the browser. Just use the ServletResponse object to do so, just like you would inside a servlet.
You may have to cast the ServletResponse to a HttpResponse to obtain a PrintWriter from it. Otherwise you only have the OutputStream available via getOutputStream().
Here is an example:
這個doFilter()方法檢查request參數(shù):myParam,看它是不是和"blockTheRequest"相愛南瓜燈,如果不是,這個請求會被filterChain.doFilter()方法調(diào)用,如果沒有被調(diào)用,線程掛起。如果相等,你能在ServletResponse對象中寫一寫返回給瀏覽器的數(shù)據(jù)。
必須將ServletResponse強制轉(zhuǎn)換為HttpResponse才可以從中獲取PrintWriter。 否則,只能通過getOutputStream()獲得OutputStream。
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
String myParam = request.getParameter("myParam");
if(!"blockTheRequest".equals(myParam)){
filterChain.doFilter(request, response);
return;
}
HttpResponse httpResponse = (HttpResponse) httpResponse;
httpResponse.getWriter().write("a different response... e.g in HTML");
}
在web.xml里配置過濾器/攔截器
<filter>
<filter-name>myFilter</filter-name>
<filter-class>servlets.SimpleServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>*.simple</url-pattern>
</filter-mapping>
通過這種配置,所有URL以.simple結(jié)尾的請求都將被servlet過濾器攔截。