我已经设法通过实现自己的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
. RequestMapping
Spring 创建一个默认映射处理程序,将组件扫描找到的所有s 添加到该处理程序中。我的初始设置失败的原因是这个处理程序的顺序是在mvc:resources
. 创建我自己的适配器并将其设置为在mvc:resources
允许两者工作后处理的顺序。
有关这方面的信息可以在 spring 文档19.9.1 Setting up 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"/>
更新:更改为反映Spring 3.1.x 及更高版本中所做的RequestMappingHandlerMapping
更改。RequestMappingHandlerAdapter
DefaultAnnotationHandlerMapping
AnnotationMethodHandlerAdapter