Home | 简体中文 | 繁体中文 | 杂文 | 打赏(Donations) | OSChina 博客 | Facebook | Linkedin | 知乎专栏 | Search | About

3.4. Filter

3.4.1. web.xml

配置过滤器

		
<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>cn.netkiller.Filter</filter-class>
    <init-param>
        <param-name>username</param-name>
        <param-value>netkiller</param-value>
    </init-param>
</filter>


<filter>
      <filter-name>LoginFilter</filter-name>
      <filter-class>cn.netkiller.Filter</filter-class>
</filter>
<filter-mapping>
      <filter-name>LoginFilter</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>
		
		

3.4.2. Filter 类

实现 Filter 接口

		
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init LoginFilter");
        //获取Filter初始化参数
    	String username = filterConfig.getInitParameter("username");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        //把ServletRequest和ServletResponse转换成真正的类型
        HttpServletRequest req = (HttpServletRequest)request;
        HttpSession session = req.getSession();

        //由于web.xml中设置Filter过滤全部请求,可以排除不需要过滤的url
        String requestURI = req.getRequestURI();
        if(requestURI.endsWith("login.jsp")){
            chain.doFilter(request, response);
            return;
        }

        //判断用户是否登录,进行页面的处理
        if(null == session.getAttribute("user")){
            //未登录用户,重定向到登录页面
            ((HttpServletResponse)response).sendRedirect("login.jsp");
            return;
        } else {
            //已登录用户,允许访问
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy!!!");
    }
}