知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
配置過濾器
<filter> <filter-name>LoginFilter</filter-name> <filter-class>cn.netkiller.Filter</filter-class> <init-param> <param-name>username</param-name> <param-value>netkiller</param-value> </init-param> </filter> <filter> <filter-name>LoginFilter</filter-name> <filter-class>cn.netkiller.Filter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
實現 Filter 介面
public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init LoginFilter"); //獲取Filter初始化參數 String username = filterConfig.getInitParameter("username"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //把ServletRequest和ServletResponse轉換成真正的類型 HttpServletRequest req = (HttpServletRequest)request; HttpSession session = req.getSession(); //由於web.xml中設置Filter過濾全部請求,可以排除不需要過濾的url String requestURI = req.getRequestURI(); if(requestURI.endsWith("login.jsp")){ chain.doFilter(request, response); return; } //判斷用戶是否登錄,進行頁面的處理 if(null == session.getAttribute("user")){ //未登錄用戶,重定向到登錄頁面 ((HttpServletResponse)response).sendRedirect("login.jsp"); return; } else { //已登錄用戶,允許訪問 chain.doFilter(request, response); } } @Override public void destroy() { System.out.println("destroy!!!"); } }