21

I know you can set the server.contextPath in application.properties to change the root context.

Also, I can add an additional context in the application config for Spring Boot like the following example (in Groovy) to add an "/api" to the URL mappings of the root context:

@Bean
ServletRegistrationBean dispatcherServlet() {
     ServletRegistrationBean reg = new ServletRegistrationBean(new DispatcherServlet(), "/")
        reg.name = "dispatcherServlet"
        reg.addInitParameter("contextConfigLocation", "")
        reg.addUrlMappings("/api/*")
        reg.loadOnStartup = 2
        reg
    }
}

I am trying to have a separate base URI "/api" specifically for web service calls, that I can leverage for security, etc. However using the above approach will mean that any of my URIs, web service or not, can be reached with "/" or "/api", and provides no concrete segregation.

Is anyone aware of a better approach to set a base path for all @RestController(s) using configuration, without having to formally prefix every controller with /api/? If I am forced to manually prefix the URI for each controller, it would be possible to mistakenly omit that and bypass my security measures specific to web services.

Here is a reference in Stack Overflow to the same type of question, which was never completely answered:

Spring Boot: Configure a url prefix for RestControllers

1

6 Answers 6

23

In continuation to the currently accepted solution the github issue addresses the same.

Spring 5.1 and above you can implement WebMvcConfigurer and override configurePathMatch method like below

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("/api",
                    HandlerTypePredicate.forAnnotation(RestController.class));
    }

}

Now all the @RestControllers will have /api as the prefix path alongside the path configured.

Official Documentation

1
  • I want to add a prefix on RestController only (not Controller)! really helpful. thank you
    – hynuah_iia
    May 6, 2022 at 0:13
15

There's a new solution to solve this kind of problem available since Spring Boot 1.4.0.RC1 (Details see https://github.com/spring-projects/spring-boot/issues/5004)

The solution of Shahin ASkari disables parts of the Auto configuration, so might cause other problems.

The following solution takes his idea and integrates it properly into spring boot. For my case I wanted all RestControllers with the base path api, but still serve static content with the root path (f.e. angular webapp)

Edit: I summed it up in a blog post with a slightly improved version see https://mhdevelopment.wordpress.com/2016/10/03/spring-restcontroller-specific-basepath/

@Configuration
public class WebConfig {

    @Bean
    public WebMvcRegistrationsAdapter webMvcRegistrationsHandlerMapping() {
        return new WebMvcRegistrationsAdapter() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new RequestMappingHandlerMapping() {
                    private final static String API_BASE_PATH = "api";

                    @Override
                    protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
                        Class<?> beanType = method.getDeclaringClass();
                        RestController restApiController = beanType.getAnnotation(RestController.class);
                        if (restApiController != null) {
                            PatternsRequestCondition apiPattern = new PatternsRequestCondition(API_BASE_PATH)
                                    .combine(mapping.getPatternsCondition());

                            mapping = new RequestMappingInfo(mapping.getName(), apiPattern,
                                    mapping.getMethodsCondition(), mapping.getParamsCondition(),
                                    mapping.getHeadersCondition(), mapping.getConsumesCondition(),
                                    mapping.getProducesCondition(), mapping.getCustomCondition());
                        }

                        super.registerHandlerMethod(handler, method, mapping);
                    }
                };
            }
        };
    }

}
10

Also You can achieve the same result by configuring WebMVC like this:

@Configuration
public class PluginConfig implements WebMvcConfigurer {

public static final String PREFIX = "/myprefix";

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer.addPathPrefix(PREFIX, c -> c.isAnnotationPresent(MyCustomAnnotation.class));
}

}

  1. Implement WebMvcConfigurer on any @Configuration class.
  2. Override configurePathMatch method.
  3. You can do many useful things with PathMatchConfigurer e.g. add prefix for several classes, that satisfy predicate conditions.
0
4

I had the same concern and was not a fan of the Spring EL option due to the issues documented and I wanted the prefix to be tightly controlled in the controllers but I did not want to depend on the developers doing the right thing.

There might be a better way these days but this is what I did. Can you guys see any downsides, I am still in the process of testing any side-effects.

  1. Define a custom annotation.
    This allows a developer to explicitly provide typed attributes such as int apiVersion(), String resourceName(). These values would be the basis of the prefix later.
  2. Annotated rest controllers with this new annotation
  3. Implemented a custom RequestMappingHandlerMapping

In the RequestMappingHandlerMapping, I could read the attribute of the custom annotation and modify the final RequestMappingInfo as I needed. Here are a few code snippets:

@Configuration
public class MyWebMvcConfigurationSupport extends WebMvcConfigurationSupport {

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        return new MyCustomRequestMappingHandlerMapping();
    }
}

And in the MyCustomRequestMappingHandlerMapping, overwrite the registerHandlerMethod:

private class MyCustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    private Logger myLogger = LoggerFactory.getLogger(MyCustomRequestMappingHandlerMapping.class);

    public MyCustomRequestMappingHandlerMapping() {
        super();
    }

    @Override
    protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {

        // find the class declaring this method
        Class<?> beanType = method.getDeclaringClass();

        // check for the My rest controller annotation
        MyRestController myRestAnnotation = beanType.getAnnotation(MyRestController.class);

        if (myRestAnnotation != null) {
            // this is a My annotated rest service, lets modify the URL mapping 

            PatternsRequestCondition oldPattern = mapping.getPatternsCondition();

            // create a pattern such as /api/v${apiVersion}/${resourceName}
            String urlPattern = String.format("/api/v%d/%s", 
                    myRestAnnotation.apiVersion(), 
                    myRestAnnotation.resourceName());

            // create a new condition
            PatternsRequestCondition apiPattern = 
                    new PatternsRequestCondition(urlPattern);

            // ask our condition to be the core, but import all settinsg from the old 
            // pattern
            PatternsRequestCondition updatedFinalPattern = apiPattern.combine(oldPattern);

            myLogger.info("re-writing mapping for {}, myRestAnnotation={}, original={}, final={}", 
                    beanType, myRestAnnotation, oldPattern, updatedFinalPattern);

            mapping = new RequestMappingInfo(
                    mapping.getName(),
                    updatedFinalPattern,
                    mapping.getMethodsCondition(),
                    mapping.getParamsCondition(),
                    mapping.getHeadersCondition(),
                    mapping.getConsumesCondition(),
                    mapping.getProducesCondition(),
                    mapping.getCustomCondition()
                    );
        }

        super.registerHandlerMethod(handler, method, mapping);
    }
}
4

Slightly less verbose solution which doesn't duplicate the logic of checking the annotation, but only changes the mapping path:

private static final String API_PREFIX = "api";

@Bean
WebMvcRegistrationsAdapter restPrefixAppender() {
    return new WebMvcRegistrationsAdapter() {
        @Override
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            return new RequestMappingHandlerMapping() {
                @Override
                protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
                    RequestMappingInfo mappingForMethod = super.getMappingForMethod(method, handlerType);
                    if (mappingForMethod != null) {
                        return RequestMappingInfo.paths(API_PREFIX).build().combine(mappingForMethod);
                    } else {
                        return null;
                    }
                }
            };
        }
    };
}

Side effects

Your error controller will also be mapped under /api/error, which breaks error handling (DispatcherServlet will still redirect errors to /error without prefix!).

Possible solution is to skip /error path when adding /api prefix in the code above (one more "if").

2

Someone has filed an issue in the Spring MVC Jira and come up with a nice solution, which I am now using. The idea is to use the Spring Expression Language in the prefix placed in each RestController file and to refer to a single property in the Spring Boot application.properties file.

Here is the link of the issue: https://jira.spring.io/browse/SPR-13882

2
  • 1
    Thanks for posting a reference to the Jira ticket Olivier. I should have posted it earlier. I had asked the same question on Springs developer forums and was prompted to open the ticket, which I did. Not sure it's a great solution, but will suffice.
    – pczeus
    Feb 29, 2016 at 12:37
  • 1
    Unfortunately, this is now broken when I use Spring HATEOAS. When I use the framework to generate the link, it picks up the Spring EL and interprets the '{' / '}' as path variables... It breaks here: github.com/spring-projects/spring-framework/blob/v4.2.4.RELEASE/… Mar 5, 2016 at 8:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.