我的项目结构如下
|源代码
|--主要
|---网络应用
|----静态
|-----CSS
|-----HTML
|-----js
我正在尝试通过 Controller 返回 HTML 资源,对于直接位于根目录下的链接没有问题,但对于其他链接,我遇到了问题。
这是我的 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");
}
}
这是我的 WebMvcConfigurerAdapter 扩展类
@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);
}
}
当我打开/或/index.html 时, Controller 返回给定值,作为返回,我得到了正确的资源。
但是当我尝试使用/support/1/xsdda 时,我被映射到/support/1/static/html/index.html 有人可以解释一下内部结构并从逻辑上指出我的错误。
谢谢!
最佳答案
在 webapp 中创建文件夹 WEB-INF 并将 HTML 文件夹放入其中
- 将解析器的前缀设置为/WEB-INF/HTML/
- 将解析器的后缀设置为.html
- 通过返回“index”来调用它
Servlet 2.4 规范是这样描述 WEB-INF 的(第 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. TheWEB-INF
node is not part of the public document tree of the application. No file contained in theWEB-INF
directory may be served directly to a client by the container. However, the contents of theWEB-INF
directory are visible to servlet code using thegetResource
andgetResourceAsStream
method calls on theServletContext
, and may be exposed using theRequestDispatcher
calls.
关于java - 无法正确映射静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796650/