Filter(過濾器)主要對(duì)請(qǐng)求到達(dá)前進(jìn)行處理,也可以在請(qǐng)求結(jié)束后進(jìn)行處理,類似于鏈?zhǔn)健R粋€(gè)請(qǐng)求可以被多個(gè)過濾器攔截到,會(huì)依次進(jìn)入各個(gè)Filter中,放行后直至進(jìn)入Servlet,Servlet處理請(qǐng)求結(jié)束后,回到各個(gè)Filter繼續(xù)執(zhí)行后面的代碼,先執(zhí)行的Filter后執(zhí)行完。
用戶權(quán)限過濾
記錄日志
字符編碼處理
@WebFilter注解
web.xml中配置
@WebFilter常用屬性
1、方式一,@WebFilter注解方式
自定義過濾器,實(shí)現(xiàn)javax.servlet.Filter接口,通過注解方式配置。攔截所有的請(qǐng)求,放行登錄頁(yè)面、登錄操作請(qǐng)求,其余請(qǐng)求需要在登錄后才可訪問。同時(shí)配置參數(shù),指定要放行的路徑和請(qǐng)求的字符集。
@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 {
// 獲取配置參數(shù)
String loginUI = config.getInitParameter("loginUI");
String loginProcess = config.getInitParameter("loginProcess");
String encoding = config.getInitParameter("encoding");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 設(shè)置請(qǐng)求的字符集(post請(qǐng)求方式有效)
request.setCharacterEncoding(encoding);
// 不帶http://域名:端口的地址
String uri = request.getRequestURI();
if (uri.contains(loginUI) || uri.contains(loginProcess)) {
// 請(qǐng)求的登錄,放行
chain.doFilter(request, response);
} else {
if (request.getSession().getAttribute("user") == null) {
// 重定向到登錄頁(yè)面
response.sendRedirect(request.getContextPath() + loginUI);
} else {
// 已經(jīng)登錄,放行
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的加強(qiáng)版;
● Filter中對(duì)權(quán)限的過濾、字符編碼的處理、日志的記錄可以看成是各個(gè)Servlet中重復(fù)代碼的抽取;
● 對(duì)于字符編碼的處理,request.setCharacterEncoding()對(duì)post方式的請(qǐng)求有效;若是get方式,可以使用new String(xxx.getBytes("iso-8859-1"), "utf-8")進(jìn)行處理,否則表單的中文會(huì)亂碼;也可以使用代理方式,每當(dāng)通過request.getParameter()時(shí)自動(dòng)進(jìn)行編碼處理;