Saturday, January 18, 2014

Java EE Tip of the Day: @WebFilter (Servlet Filter) Redirection

There is a common case to check a condition in a filter, and if the condition is not satisfied to redirect back to the context root of the application. This may be the case in a login filter, or a filter that performs some session management.

Here is a simple code example of how to perform the redirection:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 
    //TODO perform conditional check here
    if (check()) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String url = httpServletResponse.encodeRedirectURL(httpServletRequest.getContextPath());
        httpServletResponse.sendRedirect(url);
    } else {
        chain.doFilter(request, response);
    }
}

0 comments :

Popular Posts