过滤器应用——之检查用户是否登录


       刚开始接触技术,对这片领域充满了好奇,第一次写博客心里有点小激动~,开通此博客的主要目的是为了将自己学到的一些东西记录下来,这是一个复习与总结的过程,有利于巩固自己对知识的理解。俗话说的好,好记性不如烂笔头,学习——思考——总结——记录,技术的学习周期一般是这样的,希望我能坚持下去,能在技术这条路上走的更远!Say good luck to myself!

  好了,废话不多说直接进入主题:本文主要记录web开发中过滤器的应用。

  通常,我们在登录一些网站后比如说登录某论坛,如果想发表评论,系统往往会提示:“您还没有登录,请登录后在。。。。”这里系统检测用户是否登录的过程就用到了过滤器。过滤器主要是实现Filter接口,比如:

package com.chris.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

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

import org.apache.catalina.connector.Request;

import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;

public class LoginFilter implements Filter {
    
    private String sessionKey;
    private String rediretUrl;
    private String uncheckedUrls;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext=filterConfig.getServletContext();
        sessionKey=servletContext.getInitParameter("userSessonKey");
        rediretUrl=servletContext.getInitParameter("rediretUrl");
        uncheckedUrls=servletContext.getInitParameter("uncheckedUrls");
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;
        
        //1、得到用户请求路径
        String servletPath=httpServletRequest.getServletPath();
        //2、放行不需要过滤的页面,如登录界面之类的
        List<String> urls=Arrays.asList(uncheckedUrls.split(","));
        if(urls.contains(servletPath)){
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //3、从session中获取用户并判断用户是否登录过,如果没有登录过则重定向到登录界面
        Object user= httpServletRequest.getSession().getAttribute(sessionKey);if(user==null){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+rediretUrl);
            return;
        }
        
        //4、否则放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

 

文中sessionKey,rediretUrl,uncheckedUrls是初始化在web.xml中的,在LoginFilter 中通过FilterConfig对象获取这些值,这里FilterConfig类似于ServletConfig:

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>LoginFilter</display-name>
  <welcome-file-list>
    <welcome-file>login/index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
      <param-name>userSessonKey</param-name>
      <param-value>USERSESSONKEY</param-value>
  </context-param>
  <context-param>
      <param-name>rediretUrl</param-name>
      <param-value>/login/login.jsp</param-value>
  </context-param>
  <context-param>
      <param-name>uncheckedUrls</param-name>
      <param-value>/login/a.jsp,/login/login.jsp,/login/index.jsp,/login/dologin.jsp</param-value>
  </context-param>
  <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.chris.filter.LoginFilter</filter-class>      
  </filter>  
  <filter-mapping>
      <filter-name>loginFilter</filter-name>
      <url-pattern>/login/*</url-pattern>
  </filter-mapping>
</web-app>

 

 

本例子中为了方便,LoginFilter 类中的form表单的action是跳转到另一个jsp中的——dologin.jsp.

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <%
        String username = request.getParameter("username");
        if (username != null && !username.trim().equals("")) {
       //如果username不为空则将username放入到session中,以便LoginFilter 类中进行用户是否登录的判断 session.setAttribute(application.getInitParameter(
"userSessonKey"), username); response.sendRedirect("index.jsp"); }else{ response.sendRedirect("login.jsp"); } %> </body> </html>

 

到这里,一个简单的检测用户是否登录的过滤器就完成了。本人理解比较浅显,请各位大神指正!

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM