【问题标题】:Spring Rest API and static web content access without suffix无后缀的 Spring Rest API 和静态 Web 内容访问
【发布时间】:2017-08-26 16:10:36
【问题描述】:

假设我有一个名为 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.htmlindex3.html 中的另一个文件,而无需显式编写后缀html。我尝试实现访问类似的网页

localhost:8080/application/index2

不使用另一个@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

【问题讨论】:

  • @AbhijitSarkar 不,我不使用 Spring Boot :)
  • 好的,我撤回了我的近距离投票,因为我提到的答案是特定于 Boot 的。

标签: java html spring spring-mvc resources


【解决方案1】:

你可以使用类似的东西,

@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 映射到 login.html,welcome 映射到welcome.html。它不需要@RequestMapping,但仍需要显式映射。

【讨论】:

  • 可能是最好的答案。虽然看起来我不会避免手动解析特定的 URL 来查看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 2016-05-07
  • 2017-11-06
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2019-03-24
相关资源
最近更新 更多