Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Spring REST controllers base url without changing the static resources base url

Tags:

spring

I have a spring boot application with bunch of rest controllers (@RestController).

I use the following property in application.properties file to set the base url:

server.context-path=api

This property changes the base url for my static resources, too. I don't want them to change, how can I do that?

Note1 Why I want to do that? I want to serve a single page application (react app) on my server, and I want most of my requests made to /api/** to be authorized. I want all other GET requests to be handled by the react router. This is why I don't want the base URL for my static resources to change.

like image 715
Arian Avatar asked Nov 23 '17 19:11

Arian


2 Answers

You should not use this property as it changes the context path for the whole application.

Why not simply specify /api/yourResource in the RequestMapping annotation such as :

@RestController
@RequestMapping("/api/oneController")
public class OneController { ... }

.....

@RestController
@RequestMapping("/api/anotherController")
public class AnotherController { ... }
like image 188
davidxxx Avatar answered Sep 30 '22 12:09

davidxxx


You can use

spring.data.rest.base-path=/api

in your application properties with

@BasePathAwareController 

on your controller class.

When you use

server.context-path=ctx

the context path applies to the whole application including

  • static resources
  • end points created with @Controller
  • end points created with @RestController
  • end points created with @BasePathAwareContoller
  • end points created with @RepositoryRestController
  • end points created with @RepositoryRestResource

When you use

spring.data.rest.base-path=/api

the prefix applies to

  • end points created with @BasePathAwareContoller
  • end points created with @RepositoryRestController
  • end points created with @RepositoryRestResource

And you can use both

server.context-path=ctx
spring.data.rest.base-path=/api

to apply a prefix like /ctx/api/

like image 29
vsoni Avatar answered Sep 30 '22 14:09

vsoni