[Servlet] 필터 사용 예시

web.xml

필터 인터페이스 구현 외에도 서블릿 컨테이너가 필터를 찾아서 호출할 수 있도록 편집해야 함.

<filter>
    <filter-name>time</filter-name>
    <filter-class>com.filter.TimerFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>time</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>char</filter-name>
    <filter-class>com.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>charset</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>char</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
      <filter-name>login</filter-name>
    <filter-class>com.filter.LoginFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>login</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

타이머필터

public class TimerFilter implements Filter {
    private FilterConfig config;

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        //request 필터
        long start = System.currentTimeMillis();

        //다음필터 또는 필터의 마지막이면 서블릿(JSP)실행
        chain.doFilter(req, resp);

        //response 필터
        long end = System.currentTimeMillis();
        String uri;
        if(req instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest)req;
            uri = request.getRequestURI();

            ServletContext context = config.getServletContext();
            context.log(uri + " 실행시간:" + (end-start)+"ms 시간이 소요됨");
        }
    }
    public void destroy() {}
}

로그인필터

public class LoginFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpSession session = request.getSession();

        String userId = (String)session.getAttribute("userId");

        String[] uris = {"/sbbs/created.kh", "/sbbs/article.kh"};
        boolean flag = false;
        String uri = request.getRequestURI();
        for(String s : uris) {
            if(uri.indexOf(s) != -1) {
                flag = true;
                break;
            }
        }

        if(userId == null && flag) {
                RequestDispatcherrd = request.getRequestDispatcher("/memView/login.jsp");
            rd.forward(req, resp);
        } else {
            chain.doFilter(req, resp);
        }
    }

    public void destroy() {
    }
}

케릭터 셋 필터

public class CharacterEncodingFilter implements Filter {
    private String charset;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;

        request.setCharacterEncoding(charset);

        chain.doFilter(req, resp); //chain.doFilter() : 다음필터를 호출한다. 없으면 servlet/jsp
    }

    public void init(FilterConfig config) throws ServletException {
        charset = config.getInitParameter("charset");
        if(charset == null)
            charset = "utf-8";
    }
}