Nicolas Zozol
Nicolas Zozol

Reputation: 7048

Invoke servlet Filters from another servlet

I'm working on a CMS.

My code is inside the doGet() function of a servlet invoked at url "/market". I want a HttpServletRequestWrapper that would pass through all filters set for url "/page".

I expect these filters would update the request, so that an annotation processor could later inject dependencies with correct values.

I'm in a Tomcat server, so I should be able to cast to the right special object, and I don't have to be compliant to other servers.

An associated question is that using req.getRequestDispatcher(path).forward(requestWrapper, responseWrapper);, I was expecting the filters to be invoked. Should they ? The javadoc says:

This method allows one servlet to do preliminary processing of a request

Upvotes: 1

Views: 154

Answers (1)

BalusC
BalusC

Reputation: 1109725

Filters are by default mapped on the REQUEST dispatcher only. The below example of a filter mapping

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

is implicitly equivalent to

<filter-mapping>
    <filter-name>yourFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

This means, the filter is only triggered on the "raw" incoming request, not on a forwarded request.

There are three more dispatchers: FORWARD, INCLUDE and ERROR. The RequestDispatcher#forward() triggers the FORWARD dispatcher. If you'd like to let your filter hook on that as well, then just add it:

<filter-mapping>
    <filter-name>yourFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

Note that you need to explicitly specify the REQUEST dispatcher here, otherwise it would assume that you're overriding it altogether and are only interested in FORWARD dispatcher.

Inside the filter, if you'd like to distinguish between a REQUEST and FORWARD, then you can then check that by determining the presence of a request attribute keyed with RequestDispatcher#FORWARD_REQUEST_URI

String forwardRequestURI = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);

if (forwardRequestURI != null) {
    // Forward was triggered on the given URI.
}

Upvotes: 1

Related Questions