therrin150 therrin150 - 1 year ago 294
Java Question

Spring Boot: Configure a url prefix for RestControllers

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...

In my Spring Boot application, I'm trying to figure out how to configure a unique url prefix for all of my RestControllers.

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/*".

I know how to change the app's default context through, 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.

Answer Source

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)

...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).

e.g. /web/index, /web/error; as well as: /api/v1/something, /api/v1/something-else.

Having a nice package convention will help you not to get lost with so many controllers.

NOTE: Remember you DO NOT need to repeat the same context in every single method, but just "rest of the URL".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download