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.

2
  • 1
    Why use different URLs instead of serving different representations from the same URLs using content negotiation? Commented Apr 3, 2015 at 20:46
  • If you are using Spring Boot and Spring Data Rest then I would suggest adding this line to the application.properties : spring.data.rest.basePath=/api Commented Oct 23, 2019 at 19:05

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.