Spring Boot:为RestControllers配置url前缀 [英] Spring Boot: Configure a url prefix for RestControllers
问题描述
我不是Spring专家,而且它是黑盒子,即使使用Spring的文档,我也很难自己解决问题。有时候,我只是不知道我在寻找什么才能开始我的搜索......
I'm no Spring expert, and being the black box that it is, it's been hard trying to figure things out on my own, even with Spring's documentation. Sometimes, I just have no idea what I'm looking for in order to start my search...
在我的Spring Boot应用程序中,我想弄清楚如何为我的所有RestControllers配置唯一的url前缀。
In my Spring Boot application, I'm trying to figure out how to configure a unique url prefix for all of my RestControllers.
我真正想要的就是从根上下文/中提供静态内容,但可以从不同的上下文访问我的RestController端点,说/ api / *。
All I'm really after here is to have my static content served up from the root context, "/", but have my RestController endpoints accessible from a different context, say "/api/*".
我知道如何通过application.properties更改应用程序的默认上下文,但这并不是我所追求的。当谈到servlet,映射等时,我在这里表现出我的无知,因为我说我正试图为两种不同类型的内容获得两种不同的上下文。
I know how to change the app's default context through application.properties, but that isn't quite what I'm after. I'm showing my ignorance here when it comes to servlets, mappings, etc, as I say that I'm trying to get two different contexts for two different types of content.
推荐答案
我认为这是一个有效点,尽管将它分成两个(或更多应用程序)是很常见的。假设您要处理(1)提供HTML / CSS / JS的网站和(2)REST API。在你的控制器上你用 @RequestMapping
来定义上下文(你不能有两个,所以那些将在不同的控制器中,再次,取决于你正在努力实现):
I think that's a valid point, although it's common to have it separated as two (or more applications). Let's assume you want to handle (1) a Website serving HTML/CSS/JS and (2) a REST API. On top of your controllers you define "the context" by using @RequestMapping
(you can't have two, so those will be in different controllers, again, depending on what you are trying to achieve):
-
@RequestMapping(/ web)
-
@RequestMapping(/ api / v1)
@RequestMapping(/web)
@RequestMapping(/api/v1)
...然后在这些控制器中,在方法中,你可以再次使用 @RequestMapping(value =/ index,method = RequestMethod.GET)分配其余的URL )
。
...and then inside those controllers, in the methods, you ca assign the "rest of the URL", again by using @RequestMapping(value = "/index", method = RequestMethod.GET)
.
例如 / web / index
, / web / error
;以及: / api / v1 / something
, / api / v1 / something-else
。
有一个很好的软件包约定将帮助你不要迷失这么多控制器。
Having a nice package convention will help you not to get lost with so many controllers.
注意:请记住,您不需要在每种方法中重复相同的上下文,只需要其余的URL。
NOTE: Remember you DO NOT need to repeat the same context in every single method, but just "rest of the URL".
这篇关于Spring Boot:为RestControllers配置url前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!