基于代码的Servlet Initializer的行为与web.xml不同

时间:2016-09-21 12:19:45

标签: spring spring-mvc

使用AbstractAnnotationConfigDispatcherServletInitializer将基于Spring xml的servlet配置转换为基于代码/注释的初始化时,我遇到了一个奇怪的问题

编辑: 代码构建正常,但请求映射无法正常工作。在基于代码的配置中,如果我将请求映射到" / *" and not "/", however as i want to serve up JSP pages with a view resolver I cant use "/ *"它将仅处理请求。因为它阻止了它正常运作。

谁能看到我做错了什么? Spring版本是3.2.4

基于XML的servlet初始化

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">

<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </init-param>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>my.package.SpringConfig</param-value>
    </init-param>
    <init-param>
        <param-name>dispatchOptionsRequest</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

基于代码的servlet初始化

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[] { SpringConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
    registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    registration.setInitParameter("dispatchOptionsRequest", "true");
    registration.setLoadOnStartup(1);
}

}

0 个答案:

没有答案