Forward request from a filter

Viewed 28631

I need to forward my request (to a jsp but I don't think it's matter) from an http.Filter if the URI of the original request pass some validation that my filter runs.

I found this page that faced similar task

Still I need to figure the following:

  1. How can I get ServletContext in doFilter() method (in order to call forward API) getServletContext() is not recignized

  2. Do I have to call chain.doFilter() before the forward, after the forward or not at all? In addition do I have to call chain.doFilter() if my validation passed or only if it fails (because in this case I won't continue to forward my page)?

This question actually continue this thread, to be more obvious, the code could be something like:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = ((HttpServletRequest)request);
            String requestURI = httpServletRequest.getRequestURI();
            String contextPath = httpServletRequest.getContextPath();
            if (<this is my implementation of the validation of this filter>){                                      
                getServletContext().getRequestDispatcher(
                "MySpecific.jsp").forward(request,response);

            }

        }
        chain.doFilter(request,response);

    }
2 Answers
Related