通过AbstractAnnotationConfigDispatcherServletInitializer

时间:2015-10-07 20:47:06

标签: spring-mvc

嗨,我有一个奇怪的问题,

我正在遵循本教程(http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/),在步骤5中,配置初始化器类有两种方法:

1使用WebAppInitializer(我的代码如下)

public class SpindleSpringWebAppInitializer implements WebApplicationInitializer {

public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
    appContext.register(AppConfig.class);
    appContext.setServletContext(servletContext);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
            "SpringDispatcher", new DispatcherServlet(appContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}
  1. 使用AppInitializer扩展AbstractAnnotationConfigDispatcherServletInitializer(我的代码在这里)

    public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { AppConfig.class };
    }
    
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }
    
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
    
    }
    
  2. 这是我的AppConfig.java

    @Configuration
    @EnableWebMvc
    public class AppConfig extends WebMvcConfigurerAdapter{
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
        }
    
    
        @Bean
        public ViewResolver viewResolver() {
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setViewClass(JstlView.class);
            viewResolver.setPrefix("/WEB-INF/views/");
            viewResolver.setSuffix(".jsp");
            return viewResolver;
        }
    
        @Bean
        public MessageSource messageSource() {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            messageSource.setBasename("messages");
            return messageSource;
        }
    }
    

    Thing是当我使用第一种方法时一切正常,但当我使用第二种方法时,我得到404(描述所请求的资源不可用)。我没有其他错误,我不知道如何调试它。我不打扰,但我正在尝试将Spring Security实现到代码中,因为我理解secon类型的初始化程序是现在的优先类型。

    我正在使用Maven,STS,Pivotal tc Servert Developer Edition。感谢您的任何反馈。

1 个答案:

答案 0 :(得分:1)

问题解决了。目标文件夹仍保留web.xml和context.xml文件。删除目标文件夹并重新安装应用程序是正确的做法