Multiple SpringDispatcherServlet to handle different url

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>

Answers


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.)


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.


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.


Depends on your needs of course, but in most cases better to have one servlet.

So you can simplify you config to:

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

<servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/url2/*</url-pattern>
    <url-pattern>/url1/*</url-pattern>
</servlet-mapping> 

Need Your Help

BigQuery - Check if table already exists

google-api export google-bigquery google-cloud-storage

I have a dataset in BigQuery. This dataset contains multiple tables.