首页 > 其他 > 详细

servlet拦截器

时间:2014-08-05 22:09:30      阅读:662      评论:0      收藏:0      [点我收藏+]

servlet拦截未登录的用户请求

java代码:

package com.gavin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession session = request.getSession(true);
        String username = (String) session.getAttribute("username");// 
        String url = request.getRequestURI();
        if (username == null || username.equals("")) {
            // 判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
            if (url != null && !url.equals("") && (url.indexOf("Login") < 0 && url.indexOf("login") < 0)) {
                response.sendRedirect("login.jsp");
                return;
            }
        }
        // 已通过验证,用户访问继续
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

}

 

web.xml配置

 <filter>
  <filter-name>loginFilter</filter-name>
  <filter-class>com.gavin.filter.LoginFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>loginFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 

servlet拦截器,布布扣,bubuko.com

servlet拦截器

原文:http://www.cnblogs.com/gavinYang/p/3893205.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!