spring boot:将REST与静态内容分开 [英] spring boot: separate REST from static content

查看:48
本文介绍了spring boot:将REST与静态内容分开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 spring-boot-starter-data-rest 和 spring-boot-starter-web.我使用 CrudRepository 做了一个简单的项目,让 spring boot 生成其余的请求映射.

I'm using spring-boot-starter-data-rest and spring-boot-starter-web. I've made a simple project using a CrudRepository, letting spring boot generate the rest request mappings.

现在,我想添加一个客户端 - 进行其余调用 - 位于 ./ 下.因此,我正在尝试使用 /apirest 调用(并且只有那些!)前缀路径.

Now, I want to add a client -- making the rest calls -- live under ./. Hence, I'm trying to prefix the paths for the rest calls (and only those!) with /api.

我已经尝试了以下答案:如何在 Spring Boot 中为所有控制器指定前缀?使用 application.properties 文件中的设置

I've tried the answers from : How to specify prefix for all controllers in Spring Boot? using settings in the application.properties file

  • server.contextPath=/api/*
  • spring.data.rest.basePath=/api/*.

但是仍然没有使用 ./获取静态内容(例如 index.html、*.js、*.css).网址也以/api/"为前缀.其余调用在/api/foos 下正确提供.

But still the static content (e.g. index.html, *.js, *.css) is not fetched using ./. There urls are also prefixed by "/api/". The rest calls are properly served under /api/foos.

有没有办法告诉 spring 不要将指向位于 src/main/resources/public 中的源的 url 视为rest-controllers"?

Is there a way to tell spring not to treat urls that lead to sources located in src/main/resources/public as 'rest-controllers'?

更新

设置属性
spring.data.rest.basePath=/api/*
完美地工作.(我的沙箱中仍然有一个覆盖此设置的编程 bean 配置).

Setting the property
spring.data.rest.basePath=/api/*
works perfectly. (I still had a programmatic bean configuration in my sandbox overriding this setting).

推荐答案

Spring 控制器旨在为 HTML 和 JSON/XML 提供服务.第一个是通过 Spring MVC 视图和 Thymeleaf 等模板引擎完成的,后者完全由 Spring 和 @RestController 处理.

Spring controllers are made for serving both HTML and JSON/XML. The first one is done via Spring MVC Views and some template engine like Thymeleaf, the latter is handled entirely by Spring and @RestController.

没有办法只为返回 JSON 或 XML 数据的控制器设置上下文路径,其他控制器也没有,这也适用于静态内容.你通常做的是有一些包含你想要的 API 前缀的静态变量,并在控制器的 @RequestMapping 中使用它.即

There's no way to have a context path for only the controllers that returns JSON or XML data, and not for the other controllers as well, this also goes for static content. What you typically do is have some static variable containing the prefix you want for your APIs, and the use that in the controller's @RequestMapping. i.e.

@RestController
@RequestMapping(MyConstants.API_LATEST + "/bookings")
public class MyBookingsController {
    ...
}

无论如何,您可能想用这些方法来解决前缀问题.当您有重大更改时,通常必须支持较旧的 API 版本,至少在一段时间内是这样.

You probably want to approach the prefix problem with something along these lines anyway. It is common to have to support older API versions when you have breaking changes, at least for some time.

这篇关于spring boot:将REST与静态内容分开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆