一.Hello Filter
1.編寫FirstFilter
public class FirstFilter implements Filter {
@Override
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
//doFilter()方法中的req參數(shù)的類型是ServletRequest误墓,需要轉(zhuǎn)換為HttpServletRequest類型方便調(diào)用某些方法
String ip = request.getRemoteAddr();
//獲取用戶的ip
String url = request.getRequestURL().toString();
//獲取用戶訪問的頁面地址
System.out.printf("%s %s 訪問了%s%n",date,ip,url);
//在控制臺打印出來
chain.doFilter(request,response);
//過濾器放行
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
//與servlet需要配置自啟動才會隨著tomcat的啟動而執(zhí)行init()方法不一樣,F(xiàn)ilter一定會隨著tomcat的啟動自啟動
}
2.配置web.xml
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
二.中文處理
創(chuàng)建一個 EncodingFilter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
配置web.xml
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三.登陸驗證
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String uri = request.getRequestURI();
if (uri.endsWith("login.html") || uri.endsWith("login")) {
chain.doFilter(request, response);
return;
}
String userName = (String) request.getSession().getAttribute("userName");
if (null == userName) {
response.sendRedirect("login.html");
return;
}
chain.doFilter(request, response);
}