java web项目中的拦截未登录用户的问题

来源:互联网 发布:汽车修理软件 编辑:程序博客网 时间:2024/06/05 16:09
  • 在项目运行的开始,是先加载在web.xml文件中注册的监听器listener(首先执行其contextInitialized())方法,然后加载配置在web.xml文件
    中的拦截器filter(先执行其init()方法,继而执行其doFilter()方法),我们一般会把项目初始时就要加载进项目的内容写在监听器contextInitialized()中,例如初始化数据库源,加载.propertirs文件等,把需要拦截的请求写在拦截器的doFilter()方法中,例如拦截未登录的用户。
    一般的web项目我们都会拦截那些未登录的用户去查看我们登录后的界面。如何防止呢?我们可以把项目的登录页面的请求或者一些相应的页面请求的url在某个.properties文件中,在监听器的contextInitialized()方法中读取这些url,继而在配置拦截器filter的时候判断获取的url是否在.properties文件中,如果在,就调用不拦截(调用FilterChain.doFilter()),如果不在,就判断是否已经登录。
    源码如下

    1、监听器

@Overridepublic void contextInitialized(ServletContextEvent event) {    ServletContext servletContext = event.getServletContext();    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);    SpringWebApplicataionContext.setContext(context);    try{        //把项目一开始需要加载的请求写在white_url.txt中,然后读取文件中的内容,        //把内容写进数组里(Env.WHITE_URL是一个list)        List<String> lines = FileUtils.readLines(new ClassPathResource("/conf/white_url.txt").getFile());        if (ArrayUtil.isNotEmpty(lines)) {            for (String line : lines) {                if (!StringUtils.startsWith(line, "#")&&StringUtils.isNotBlank(line)) {                    Env.WHITE_URL.add(line);                }            }        }        System.out.println("-----white url--------");        ArrayUtil.print(Env.WHITE_URL, false);        //初始化数据源        JDBC jdbc=SpringWebApplicataionContext.getJdbc();        jdbc.query(DS, "select sysdate from dual");        } catch (Exception e) {            log.error("", e);            throw new RuntimeException(e);        }
2、拦截器
@Overridepublic void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {    HttpServletRequest request = (HttpServletRequest) req;    HttpServletResponse response = (HttpServletResponse) resp;    HttpSession session = request.getSession();    String uri = request.getServletPath();    // jsp或do,需要拦截    if (StringUtils.endsWith(uri, "jsp") || StringUtils.endsWith(uri, "do")) {        // 如果白名单有的。则放过        if (Env.WHITE_URL.contains(uri)) {                chain.doFilter(req, resp);            } else {                //判断是否登录                Object loginForm = session.getAttribute("loginForm");                if (loginForm != null) {                    chain.doFilter(req, resp);                } else {                    response.sendRedirect(request.getContextPath()+ "/timeout.jsp");                }            }    } else {        chain.doFilter(req, resp);    }}
0 0
原创粉丝点击