How to set base url for rest in spring boot?

后端 未结 18 2315
日久生厌
日久生厌 2020-11-28 03:23

I\'m trying to to mix mvc and rest in a single spring boot project.

I want to set base path for all rest controllers (eg. example.com/api) in a single place (I don\'

相关标签:
18条回答
  • 2020-11-28 03:41

    A bit late but the same question brought me here before reaching the answer so I post it here. Create (if you still don't have it) an application.properties and add

    server.contextPath=/api
    

    So in the previous example if you have a RestController with @RequestMapping("/test") you will access it like localhost:8080/api/test/{your_rest_method}

    question source: how do i choose the url for my spring boot webapp

    0 讨论(0)
  • 2020-11-28 03:42

    I found a clean solution, which affects only rest controllers.

    @SpringBootApplication
    public class WebApp extends SpringBootServletInitializer {
    
        @Autowired
        private ApplicationContext context;
    
        @Bean
        public ServletRegistrationBean restApi() {
            XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
            applicationContext.setParent(context);
            applicationContext.setConfigLocation("classpath:/META-INF/rest.xml");
    
            DispatcherServlet dispatcherServlet = new DispatcherServlet();
            dispatcherServlet.setApplicationContext(applicationContext);
    
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(dispatcherServlet, "/rest/*");
            servletRegistrationBean.setName("restApi");
    
            return servletRegistrationBean;
        }
    
        static public void main(String[] args) throws Exception {
            SpringApplication.run(WebApp.class,args);
        }
    }
    

    Spring boot will register two dispatcher servlets - default dispatcherServlet for controllers, and restApi dispatcher for @RestControllers defined in rest.xml:

    2016-06-07 09:06:16.205  INFO 17270 --- [           main] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'restApi' to [/rest/*]
    2016-06-07 09:06:16.206  INFO 17270 --- [           main] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
    

    The example rest.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
        <context:component-scan base-package="org.example.web.rest"/>
        <mvc:annotation-driven/>
    
        <!-- Configure to plugin JSON as request and response in method handler -->
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <ref bean="jsonMessageConverter"/>
                </list>
            </property>
        </bean>
    
        <!-- Configure bean to convert JSON to POJO and vice versa -->
        <bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        </bean>
    </beans>
    

    But, you're not limited to:

    • use XmlWebApplicationContext, you may use any else context type available, ie. AnnotationConfigWebApplicationContext, GenericWebApplicationContext, GroovyWebApplicationContext, ...
    • define jsonMessageConverter, messageConverters beans in rest context, they may be defined in parent context
    0 讨论(0)
  • 2020-11-28 03:42

    server.servlet.context-path=/api would be the solution I guess. I had the same issue and this got me solved. I used server.context-path. However, that seemed to be deprecated and I found that server.servlet.context-path solves the issue now. Another workaround I found was adding a base tag to my front end (H5) pages. I hope this helps someone out there.

    Cheers

    0 讨论(0)
  • 2020-11-28 03:43

    You can create a base class with @RequestMapping("rest") annotations and extend all you other classes with this base class.

    @RequestMapping("rest")
    public abstract class BaseController {}
    

    Now all classes that extend this base class will be accessible at rest/**.

    0 讨论(0)
  • 2020-11-28 03:53

    For spring boot framework version 2.0.4.RELEASE+. Add this line to application.properties

    server.servlet.context-path=/api
    
    0 讨论(0)
  • 2020-11-28 03:53

    Since this is the first google hit for the problem and I assume more people will search for this. There is a new option since Spring Boot '1.4.0'. It is now possible to define a custom RequestMappingHandlerMapping that allows to define a different path for classes annotated with @RestController

    A different version with custom annotations that combines @RestController with @RequestMapping can be found at this blog post

    @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();
                            if (AnnotationUtils.findAnnotation(beanType, RestController.class) != 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);
                        }
                    };
                }
            };
        }
    }
    
    0 讨论(0)
提交回复
热议问题