我設法通過實施我自己的Controller
和Config
來找到解決方案。
視圖-servlet.xml中
<mvc:resources mapping="/static/**" location="/static/"/>
<context:component-scan base-package="com.example.web.view"/>
com.example.web.view.ViewConfig
@Configuration
public class ViewConfig {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/views/");
vr.setSuffix(".jsp");
return vr;
}
@Bean RequestMappingHandlerMapping requestMappingHandlerMapping(){
return new RequestMappingHandlerMapping();
}
@Bean RequestMappingHandlerAdapter requestMappingHandlerAdapter(){
RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
adapter.setOrder(2); //process after mvc:resources
return adapter;
}
}
com.example.web.view.ViewController
@Controller
public class ViewController {
@RequestMapping(value = "**/")
public String all(HttpServletRequest request) {
String path = request.getRequestURI().replace(request.getContextPath(),"");
return path.endsWith("/") ? path +"index" : path;
}
}
魔術是在ViewConfig
上設置適配器上的訂單值。 Spring創建一個默認的映射處理程序,所有由組件掃描找到的RequestMapping
被添加到。我最初設置失敗的原因是這個處理程序的排序是在mvc:resources
之前註冊的。在mvc:resources
之後創建我自己的適配器並設置其處理順序,以使兩者都可以工作。
有關這方面的信息可以在春季文檔19.9.1 Setting up the dispatcher for annotation support中找到。
當然的ViewConfig也可以純粹的XML來實現:
<mvc:resources mapping="/static/**" location="/static/"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="order" value="2"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="com.example.web.view"/>
更新:更改爲RequestMappingHandlerMapping
和RequestMappingHandlerAdapter
從DefaultAnnotationHandlerMapping
和AnnotationMethodHandlerAdapter
反映春季3.1.X及以上所做的更改。