filter 拦截器

说明:仅供自己学习理解笔记使用

filter拦截器必须实现 filter接口:

例子:

package com.yjdgis.common.web.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 UserLoginFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();

        System.out.println(req.getRequestURI());

        if (null != session.getAttribute("loginUser")) {
            chain.doFilter(request, response);
            return;
        }
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendRedirect(req.getContextPath() + "/login/managerLogin");
    }

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

}

实现上面的三个方可以可以对拦截到的请求做出相应的处理,过程:

请求——》拦截器1——》拦截器2——》.......最后的资源——》......——》拦截器2——》拦截器1——》视图

每一个拦截器要有拦截器链(调用chain.doFilter(request, response))才能传播下去找下一个拦截器或资源。

web.xml中注册拦截器

<filter>
    <filter-name>userLoginFilter</filter-name>
    <filter-class>com.yjdgis.common.web.filter.UserLoginFilter</filter-class>
 </filter>

<filter-mapping>
    <filter-name>userLoginFilter</filter-name>
    <url-pattern>/jsp/*</url-pattern>
 </filter-mapping>

posted @ 2013-03-26 11:17  hwj2wj  阅读(265)  评论(0编辑  收藏  举报