关闭

拦截器的使用

标签: stringfilterclasssessionpathnull
207人阅读 评论(0) 收藏 举报

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);
 }

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:43466次
    • 积分:640
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:1篇
    • 译文:0篇
    • 评论:6条