简体   繁体   中英

Java Servlet: pass a request back to default processing

I want a Servlet to handle requests to files depending on prefix and extension, eg

prefix_*.xml

Since mapping on beginning AND end of request path is not possible, I have mapped all *.xml requests to my Servlet. The question now is: how can I drop out of my servlet for XML files not starting with "prefix_", so that the request is handled like a "normal" request to an xml file?

This is probably quite simple but I do not seem to be able to find this out... :-/

Thanks a lot in advance

another solution (maybe fits for you) is if you are using/plan to use an Apache in front of that web container instance you could use the rewrite module of apache. Rewriting the url to something more easy to handle for the Webapp container.

Hope this helps. David.

Not shure, but once you catch all *.xml requests you can inspect the request again in your code via HttpServletRequest.getRequestURI()

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri =req.getRequestURI();
        int i = uri.lastIndexOf('/');
        int j = uri.lastIndexOf('.', i);
        if (uri.substring(i+1, j).startsWith("prefix_")) {
            // your code
        }
    }

(code not tested, only an idea ...)

I would strongly suggest using a proper MVC framework for this. As you've discovered, the flexibility of the standard servlet API is very limited when it comes to request dispatching.

Ideally, you would be able to use your existing servlet code in combination with an MVC framework, with the framework doing the diapcthing based on path pattern, and your servlets doing the business logic. Luckily, Spring MVC allows you to do just that, using the ServletForwardingController. It'd be a very lightweight spring config.

So you'd have something like this in your web.xml:

<servlet>
   <servlet-name>myServlet</servlet-name>
   <servlet-class>foo.MyServlet</servlet-class>
</servlet>

<servlet>
   <servlet-name>spring</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<url-mapping>
   <servlet-name>spring</servlet-name>
   <url-pattern>*</url-pattern>
</url-mapping>

You would then have a WEB-INF/spring-servlet.xml file like this:

<beans>
    <bean name="/prefix*.xml" class="org.springframework.web.servlet.mvc.ServletForwardingController">
       <property name="servletName" value="myServlet"/>
    </bean>
</beans>

And that would be pretty much it. All requests for /prefix*.xml would go to myServlet, and all others would fall through to the container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM