当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Unable to Map static resource correctly

问题描述:

My Project structure is as follows

|src

|--main

|---webapp

|----static

|-----CSS

|-----HTML

|-----js

I am trying to return an HTML resource via my controller for links that are directly under root there is no issue but for other links, I am facing problems.

Here is my controller

@Controller

public class HtmlServer {

@RequestMapping({"/", "/index", "/index.html", "/index.jsp", "/home","/home.html","/home.jsp"})

public ModelAndView index() {

return new ModelAndView("html/index.html");

}

@RequestMapping(method = RequestMethod.GET, value = "/support/{id}/{accessToken}")

public ModelAndView start(@PathVariable Long id, @PathVariable String accessToken) {

return new ModelAndView("html/index.html");

}

}

Here is my WebMvcConfigurerAdapter extending class

@Component

@ConfigurationProperties

@Configuration

@EnableWebMvc

public class ApplicationConfig extends WebMvcConfigurerAdapter {

@Bean

public InternalResourceViewResolver internalResourceViewResolver(){

InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();

internalResourceViewResolver.setPrefix("static/");

return internalResourceViewResolver;

}

@Override

public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

configurer.enable();

}

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/js/**").addResourceLocations("static/js/")

.setCachePeriod(0);

registry.addResourceHandler("/css/**").addResourceLocations("static/css/")

.setCachePeriod(0);

registry.addResourceHandler("/support/**").addResourceLocations("/static/")

.setCachePeriod(0);

}

}

When I open / or /index.html the controller returns the given value and in return i am served the correct resource.

But when I try to use /support/1/xsdda I am mapped to /support/1/static/html/index.html Can someone explain the internals and logically point out my mistake.

Thanks!

网友答案:

Create folder WEB-INF inside webapp and put your HTML folder inside it

  • set prefix of resolver to /WEB-INF/HTML/
  • set suffix of resolver to .html
  • call it by returning "index"

The Servlet 2.4 specification says this about WEB-INF (page 70):

A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

分享给朋友:
您可能感兴趣的文章:
随机阅读: