假设我有名为 application
的 Spring Rest API及其请求映射到 /api
。这意味着我调用例如 GET
获取用户列表的方法:
localhost:8080/application/api/users
工作顺利。我的目标是让简单的静态 html 文件与此 API 能够相互引用。我需要找到index.html
文件并将其设为主页。
localhost:8080/application/
它正确地显示了我 index.html
使用:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String homePage(ModelMap model) {
return "home";
}
和
@Configuration
@ComponentScan(basePackages = "net.nichar.application")
@EnableWebMvc
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
我遇到困难的是使用 <a href=...>
进行导航覆盖同一文件夹中的另一个文件 index2.html
, index3.html
无需显式写入后缀html
。我尝试实现访问类似的网页
localhost:8080/application/index2
不使用另一个@RequestMapping(除了第一个映射主页的@RequestMapping)。
还有一个问题,有没有办法在路径导航中“跳过”文件夹?为了清楚起见,我想将这些 html 文件放入 webapp/static
文件夹,但是我必须像这样访问它们
localhost:8080/application/static/...
我曾尝试学习一些有关 Spring 资源映射的教程,但是没有一个教程描述了任何类似问题的解决方案。我不使用 Spring Boot。
感谢您的帮助。
简短地说:
如何访问 --> 中的文件:
webapp/WEB-INF/pages/index.html --> localhost:8080/application
webapp/static/index2.html --> localhost:8080/application/index2
webapp/static/index3.html --> localhost:8080/application/index3
最佳答案
你可以使用类似的东西,
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/welcome").setViewName("welcome");
registry.addViewController("/about").setViewName("about");
registry.addViewController("/contact").setViewName("contact");
}
其中登录映射到login.html,欢迎映射到welcome.html。它不需要@RequestMapping,但仍然需要显式映射。
关于java - Spring Rest API和无后缀的静态Web内容访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45897338/