views:

33

answers:

3

Is it ok to have more than 1 DispatcherServlet in web.xml to handle different URL ? What's the downside?

<servlet>
    <servlet-name>servlet1</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet>
    <servlet-name>servlet2</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>


<servlet-mapping>
    <servlet-name>servlet1</servlet-name>
    <url-pattern>/url2/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>servlet2</servlet-name>
    <url-pattern>/url1/*</url-pattern>
</servlet-mapping>
+1  A: 

Yeah, that's fine. The only downside is that the application contexts for each of the servlets won't be able to talk to each other, but it's a perfectly valid approach.

I would suggest, though, that it's generally better to have just the one DispatcherServlet, and handle all request routing within that. It's one less thing to go wrong.

skaffman
+1  A: 

Yes, it is absolutely OK. Depending on app complexity and architecture, it actually may become very useful. You can use it to structure the application on dispatcher level (rather than on controllers). Or when you want certain URL classes to have different dispatcher configuration (view resolvers, locale resolvers, etc.)

Konrad Garus
+1  A: 

You don't necessarily need multiple instances of the same servlet, unless you'd like to give them each different init-param values. I'd rather just assign different mappings to the same servlet like so:

<servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/url1/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/url2/*</url-pattern>
</servlet-mapping>

That's also perfectly valid for the case you didn't knew that.

BalusC