java - Spring Rest API和无后缀的静态Web内容访问

标签 java html spring spring-mvc resources

假设我有名为 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/

相关文章:

java - java类方法在单线程和多线程环境下如何分配内存并执行?

java - 光标的坐标位置和颜色在一定条件下变化 - JavaFX

java - 实现客户端多文件上传服务的有效方法

java - 如何检查字符串是否包含搜索项

java - Spring 启动: No matching bean found exception

html - li 列表定位行为

jquery - 使用 css 和 jquery 将图像用作单选按钮

javascript - 我怎样才能让我网站上的这个按钮重定向到网站上的另一个页面?

Java Spring Boot Hibernate、JPA、MVC、REST混淆

java - 使用 Spring XML 配置实现观察者模式?