拦截器的使用

来源:互联网 发布:php根据ip获取地区 编辑:程序博客网 时间:2024/05/16 15:29

1、在web.xml文件里面加

 <filter>
     <filter-name>AuthenticationFilter</filter-name>
     <filter-class>com.util.filter.AuthenticationFilter</filter-class>
    </filter>
    <filter-mapping>
     <filter-name>AuthenticationFilter</filter-name>
     <url-pattern>/*</url-pattern>
    </filter-mapping>

2、写拦截器代码

public abstract class HttpFilter implements Filter {
 private FilterConfig config;

 public void init(FilterConfig config) throws ServletException {
  this.config = config;
  init();
 }

 public void init() throws ServletException {
 }
 
 public ServletContext getServletContext(){
  return config.getServletContext();
 }

 public String getInitParameter(String name) {
  return config.getInitParameter(name);
 }

 public final void doFilter(ServletRequest request,
   ServletResponse response, FilterChain chain) throws IOException,
   ServletException {
  doFilter((HttpServletRequest) request, (HttpServletResponse) response,
    chain);
 }

 public abstract void doFilter(HttpServletRequest request,
   HttpServletResponse response, FilterChain chain)
   throws IOException, ServletException;

 public void destroy() {
 }
}

3、实现上面的自己写的拦截器当不是正常登录的时候放回到登录页面

public class AuthenticationFilter extends com.lyt.util.HttpFilter {

 public void doFilter(HttpServletRequest request,
   HttpServletResponse response, FilterChain chain)
   throws IOException, ServletException {
  HttpSession session = request.getSession();
  if (session.getAttribute("user") == null) {
   String path = request.getServletPath();
   if (!path.startsWith("/login.jsp") ) {
             response.sendRedirect(request.getContextPath() + "/login.jsp");
    return;
   }
  }
  chain.doFilter(request, response);
 }

}