In this example, we will understand the effect of using method setUseTrailingSlashMatch() of RequestMappingHandlerMapping . This setting specifies whether to match the URLs irrespective of the presence of a trailing slash. If enabled a handler method mapped to "/users" also matches to the uri "/users/" (other than "/user"). The default value is true.
Example
A controller
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/employee")
public String employeeHandler() {
return "response from employeeHandler()";
}
}
Java Config:
First we are going to see the default behavior when setUseTrailingSlashMatch is set to false.
@Configuration
@ComponentScan
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
As seen in above outputs, both paths are mapped to our single handler method employeeHandler()
Let's set setUseTrailingSlashMatch to false.
Setting setUseTrailingSlashMatch=false
Let's configure RequestMappingHandlerMapping with the desired setting:
@Configuration
@ComponentScan
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseTrailingSlashMatch(false);
}
}
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.0.4.RELEASE: Spring Web MVC.
- javax.servlet-api 3.0.1 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|