8

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.

therrin150
  • 187
  • 1
  • 3
  • 7

2 Answers2

9

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

x80486
  • 5,713
  • 5
  • 38
  • 91
  • Thank you very much! I was hoping for a more global way to configure it, but I'd completely spaced being able to give the controller a path, not just its methods. This works, and is quite simple enough. =) – therrin150 Apr 04 '15 at 02:28
1

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?

Community
  • 1
  • 1
Shahin Askari
  • 103
  • 1
  • 9
  • The linked answer does not work for this case, since it will disable the serve of static content, but I've added an additional answer to that question that does not have this problem. see http://stackoverflow.com/questions/34801351/how-to-configure-a-default-restcontroller-uri-prefix-for-all-controllers/39716758#39716758 – mh-dev Sep 27 '16 at 13:59