Request is going to Struts Dispatcher

2020-04-30 23:56发布

问题:

I have both Struts 2 and Spring MVC configured. My web.xml looks like below. When I hit a REST URL to upload file, it invokes struts dispatcher instead of Spring.

URL /rest/uploadfile/iec9.pdf is going to Struts Dispatcher

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

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

<servlet>
<servlet-name>springmvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springmvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>jsonpCallbackFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>jsonpCallbackFilter</filter-name>
<url-pattern>*.json</url-pattern>
</filter-mapping>

回答1:

Your spring MVC dispatcher servlet is mapped to the subset of URLs handled by the Struts filter. As far as filter invoked before any other servlets then it will have precedence. To workaround you need to configure Struts to exclude some URLs from mapping.

<struts>
    <constant name="struts.action.excludePattern" value="/rest/?.*"/>
    ...

</struts>  


回答2:

Adding to Roman’s answer, when configuring Struts and Spring MVC in the same project, it is common to use a struts exclude filter. When the request is made Struts will try to handle the request, when it is excluded Spring MVC will take over and handle the request. Is is worth noting that the Struts exclude filter can go in a properties file, such as a struts.properties. Often Regex can be used here in order to exclude a common phrase (like if all your actions or controllers in a class share a common part, you can exclude all using the Regex).