"/" 、"/*、"/**"在spring-webmvc中的注意事项

控制器(Controller)

  • "/":拦截后端接口请求,即通过@Controller@RestController@RequestMapping标记的类,用于后端接口。

  • "/*":拦截所有请求,除了后端接口包括,资源文件、JSP页面等。

用web.xml配置,一般配置为"/"。

<servlet>
    <servlet-name>SpringMvcDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>SpringMvcDispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

如果是使用SpringBoot的项目,添加spring-boot-starter-web依赖即可,无需xml配置,默认的url-pattern也是"/”。
自动配置原理:

  1. spring-boot-starter-web包依赖了spring-webspring-webmvcspring-boot-autoconfigure
  2. spring-boot-autoconfigure包的META-INF/spring.factories文件里包含了webmvc的自动配置类org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
  3. WebMvcAutoConfiguration类标记@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class})
  4. DispatcherServletAutoConfiguration配置了DispatcherServletDispatcherServletRegistrationBean,并标记@EnableConfigurationProperties(ServerProperties.class)
  5. ServerProperties的内部类Servlet的path属性默认为"/"

拦截器(HandlerInterceptor)

  1. 定义
    spring-webmvc提供了org.springframework.web.servlet.HandlerInterceptor拦截器接口方便自定义扩展,根据不同场景实现preHandlepostHandleafterCompletion方法。

  2. 使用
    配置类实现WebMvcConfigurer接口的addInterceptors(InterceptorRegistry)方法,registry.addInterceptor(HandlerInterceptor).addPathPatterns(String... patterns)

pattern如果要匹配所有接口,注意"/*"和"/**"的区别:

  • "/*":匹配一级路径,如/add , /list

  • "/**":匹配多级路径,如/user/list,/manage/product/add

因为后端接口路径一般都是多级,比如以业务前缀区分/order/xxx、/product/xxx,或者加/api/v1区分版本等,因此应使用"/**"才能正确匹配。

原文地址:https://www.cnblogs.com/cdfive2018/p/12586560.html