访问Spring MVC应用程序中的静态index.html资源

时间:2014-10-21 15:48:26

标签: spring-mvc

我试图从浏览器访问index.html AngularJS文件。

这是我的目录树:

stephane@stephane-ThinkPad-X60:main> tree -l webapp
 └── webapp
    ├── META-INF
    │   └── MANIFEST.MF
    └── resources -> /home/stephane/dev/js/projects/angular/nitro-project/dist
        ├── index.html

Spring配置:

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    private static Logger logger = LoggerFactory.getLogger(WebInit.class);

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

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { ApplicationConfiguration.class, WebSecurityConfiguration.class };
    }

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

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

    @Override
    protected String getServletName() {
        return CommonConstants.SERVLET_NAME;
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(StandardCharsets.UTF_8.name());
        return new Filter[] { characterEncodingFilter };
    }

}

public class WebConfiguration extends WebMvcConfigurerAdapter {

    private static Logger logger = LoggerFactory.getLogger(WebConfiguration.class);

    private static final int PAGE_DEFAULT_SIZE = 20;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        PageableHandlerMethodArgumentResolver resolver = new PageableHandlerMethodArgumentResolver();
        resolver.setFallbackPageable(new PageRequest(0, PAGE_DEFAULT_SIZE));
        resolver.setMaxPageSize(50);
        argumentResolvers.add(resolver);
        super.addArgumentResolvers(argumentResolvers);
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
        // If true, the key of the message will be displayed if the key is not found, instead of throwing an exception
        messageSource.setUseCodeAsDefaultMessage(true);
        messageSource.setDefaultEncoding("UTF-8");
        // The value 0 means always reload the messages to be developer friendly
        messageSource.setCacheSeconds(0);
        return messageSource;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new SmartLocaleResolver();
    }

    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver =  new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(1024000);
        return multipartResolver;
    }

    // The locale interceptor provides a way to switch the language in any page just by passing the lang=’en’, lang=’fr’, and so on to the url
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");       
        return localeChangeInterceptor;
    }

    // Avoid caching issue with AngularJS on IE
    @Bean
    public WebContentInterceptor webContentInterceptor() {
        WebContentInterceptor interceptor = new WebContentInterceptor();
        interceptor.setCacheSeconds(0);
        interceptor.setUseExpiresHeader(true);;
        interceptor.setUseCacheControlHeader(true);
        interceptor.setUseCacheControlNoStore(true);        
        return interceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
        registry.addInterceptor(webContentInterceptor());
    }

}

浏览器返回404,控制台日志显示:

2014-10-31 18:11:31,917 DEBUG  [FilterSecurityInterceptor] Authorization successful 
2014-10-31 18:11:31,918 DEBUG  [FilterSecurityInterceptor] RunAsManager did not change Authentication object 
2014-10-31 18:11:31,918 DEBUG  [FilterChainProxy] /resources/index.html reached end of additional filter chain; proceeding with original chain 
2014-10-31 18:11:31,918 DEBUG  [DispatcherServlet] DispatcherServlet with name 'NITRo' processing GET request for [/nitro-project-rest/resources/index.html] 
2014-10-31 18:11:31,919 DEBUG  [RequestMappingHandlerMapping] Looking up handler method for path /resources/index.html 
2014-10-31 18:11:31,933 DEBUG  [RequestMappingHandlerMapping] Did not find handler method for [/resources/index.html] 
2014-10-31 18:11:31,933 DEBUG  [SimpleUrlHandlerMapping] Matching patterns for request [/resources/index.html] are [/resources/**] 
2014-10-31 18:11:31,934 DEBUG  [SimpleUrlHandlerMapping] URI Template variables for request [/resources/index.html] are {} 
2014-10-31 18:11:31,934 DEBUG  [SimpleUrlHandlerMapping] Mapping [/resources/index.html] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/resources/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@17f9eb2]]] and 1 interceptor 
2014-10-31 18:11:31,935 DEBUG  [DispatcherServlet] Last-Modified value for [/nitro-project-rest/resources/index.html] is: -1 
2014-10-31 18:11:31,937 DEBUG  [DispatcherServlet] Null ModelAndView returned to DispatcherServlet with name 'NITRo': assuming HandlerAdapter completed request handling 
2014-10-31 18:11:31,938 DEBUG  [DispatcherServlet] Successfully completed request 
2014-10-31 18:11:31,938 DEBUG  [ExceptionTranslationFilter] Chain processed normally 
2014-10-31 18:11:31,938 DEBUG  [SecurityContextPersistenceFilter] SecurityContextHolder now cleared, as request processing completed 

完整回复:

stephane@stephane-ThinkPad-X60:nitro-project-rest> curl -H "Accept:application/json" -H "Content-Type: application/json" --user nsn@nsn.com:etoile "http://localhost:8080/nitro-project-rest/index.html" -X GET -i
HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: text/html;charset=utf-8
Content-Length: 1009
Date: Sat, 08 Nov 2014 11:35:58 GMT

<html><head><title>Apache Tomcat/7.0.37 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - /nitro-project-rest/index.html</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>/nitro-project-rest/index.html</u></p><p><b>description</b> <u>The requested resource is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.37</h3></body></html>stephane@stephane-ThinkPad-X60:nitro-project-rest>

以下是我的请求尝试:

stephane@stephane-ThinkPad-X60:main> curl -H "Accept:application/json" -H "Content-Type: application/json" --user xxxxxx:xxxxxx "http://mylocalhost:8080/nitro-project-rest/resources/index.html" -X GET -i
HTTP/1.1 404 Not Found

stephane@stephane-ThinkPad-X60:main> curl -H "Accept:application/json" -H "Content-Type: application/json" --user xxxxxx:xxxxxx "http://mylocalhost:8080/nitro-project-rest/index.html" -X GET -iHTTP/1.1 404 Not Found
编辑:我刚才注意到了一些事情。当我从Maven运行时,它在Tomcat7上不起作用,如下所示:mvn clean install tomcat7:run但是当我在Maven构建之后手动部署到Tomcat7实例时,它运行正常(没有404)。

这是我的Maven pom.xml Tomcat7配置:

  <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.1</version>
    <configuration>
      <goalPrefix>tomcat7</goalPrefix>
      <path>/${project.build.finalName}</path>
      <httpsPort>8443</httpsPort>
      <keystoreFile>/home/stephane/tmp/thalasoft.keystore</keystoreFile>
      <keystorePass>mydearssl</keystorePass>
      <keystoreType>PKCS12</keystoreType>
      </configuration>
  </plugin>

0 个答案:

没有答案