Filter(過濾器)主要對請求到達前進行處理,也可以在請求結束后進行處理,類似于鏈式。一個請求可以被多個過濾器攔截到,會依次進入各個Filter中,放行后直至進入Servlet,Servlet處理請求結束后,回到各個Filter繼續執行后面的代碼,先執行的Filter后執行完。
用戶權限過濾
記錄日志
字符編碼處理
@WebFilter注解
web.xml中配置
@WebFilter常用屬性
1、方式一,@WebFilter注解方式
自定義過濾器,實現javax.servlet.Filter接口,通過注解方式配置。攔截所有的請求,放行登錄頁面、登錄操作請求,其余請求需要在登錄后才可訪問。同時配置參數,指定要放行的路徑和請求的字符集。
@WebFilter(filterName = "loginFilter",
urlPatterns = "/*",
initParams = {
@WebInitParam(name = "loginUI", value = "/home/loginUI"),
@WebInitParam(name = "loginProcess", value = "home/login"),
@WebInitParam(name = "encoding", value = "utf-8")
})
public class LoginFilter implements Filter {
private FilterConfig config;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// 獲取配置參數
String loginUI = config.getInitParameter("loginUI");
String loginProcess = config.getInitParameter("loginProcess");
String encoding = config.getInitParameter("encoding");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 設置請求的字符集(post請求方式有效)
request.setCharacterEncoding(encoding);
// 不帶http://域名:端口的地址
String uri = request.getRequestURI();
if (uri.contains(loginUI) || uri.contains(loginProcess)) {
// 請求的登錄,放行
chain.doFilter(request, response);
} else {
if (request.getSession().getAttribute("user") == null) {
// 重定向到登錄頁面
response.sendRedirect(request.getContextPath() + loginUI);
} else {
// 已經登錄,放行
chain.doFilter(request, response);
}
}
}
@Override
public void destroy() {
this.config = null;
}
}
2、方式二,web.xml方式配置
通過在web.xml文件中配置,去掉方式一中的@WebFilter注解,其余代碼相同
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>cn.edu.njit.filter.LoginFilter</filter-class>
<init-param>
<param-name>loginUI</param-name>
<param-value>/home/loginUI</param-value>
</init-param>
<init-param>
<param-name>loginProcess</param-name>
<param-value>home/login</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3、注
● Filter和Servlet比較相似,從屬性以及配置方式上可以看出,可以理解為Servlet的加強版;
● Filter中對權限的過濾、字符編碼的處理、日志的記錄可以看成是各個Servlet中重復代碼的抽取;
● 對于字符編碼的處理,request.setCharacterEncoding()對post方式的請求有效;若是get方式,可以使用new String(xxx.getBytes("iso-8859-1"), "utf-8")進行處理,否則表單的中文會亂碼;也可以使用代理方式,每當通過request.getParameter()時自動進行編碼處理;