首先在web.xml中对过滤器的监听
1 <!-- 自定义过滤器 --> 2 <filter> 3 <filter-name>AscFilter</filter-name> 4 <filter-class>com.llh.filter.AscFilter</filter-class> 5 </filter> 6 <filter-mapping> 7 <filter-name>AscFilter</filter-name> 8 <url-pattern>/main.jsp</url-pattern> 9 </filter-mapping> 10
新建一个包com.llh.filter,创建一个实现Filter接口的类
1 package com.llh.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import com.llh.entity.Student; 15 16 /** 17 * 过滤登陆 18 * 19 * @author Administrator 20 * 21 */ 22 public class AscFilter implements Filter { 23 @Override 24 public void init(FilterConfig filterConfig) throws ServletException { 25 // TODO Auto-generated method stub 26 } 27 28 @Override 29 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 30 throws IOException, ServletException { 31 // TODO Auto-generated method stub 32 HttpServletRequest request = (HttpServletRequest) req; 33 HttpServletResponse response = (HttpServletResponse) resp; 34 Student s = (Student) request.getSession().getAttribute("s"); 35 System.out.println("lanj"); 36 if(s==null){ 37 System.out.println("拦截了"); 38 response.sendRedirect("login.jsp"); 39 } 40 chain.doFilter(request, response); 41 } 42 43 @Override 44 public void destroy() { 45 // TODO Auto-generated method stub 46 } 47 48 }
过滤所有界面的编码