Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 409
therrin150 Avatar asked Apr 03 '15 20:04

therrin150


2 Answers

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

like image 65
x80486 Avatar answered Sep 16 '22 11:09

x80486


I don't know if it helps, I just posted a solution I am testing in another thread:

How to configure a default @RestController URI prefix for all controllers?

like image 33
Shahin Askari Avatar answered Sep 17 '22 11:09

Shahin Askari