This example will show how to use SimpleUrlHandlerMapping. check out HandlerMapping tutorial, to get familiar with the concept.
SimpleUrlHandlerMapping can be used to map URL patterns to handler beans.
Example
Registering SimpleUrlHandlerMapping
SimpleUrlHandlerMapping is not registered by default, so we have to do that ourselves:
@EnableWebMvc
@Configuration
public class AppConfig {
@Bean
HttpRequestHandler httpRequestHandler () {
return new MyHttpRequestHandler();
}
@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping () {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
Map<String, Object> map = new HashMap<>();
map.put("/app/**", httpRequestHandler());
mapping.setUrlMap(map);
return mapping;
}
}
We are mapping Ant-style pattern: '/app/**', which will map all URIs starting with /app.
We are also registering an implementation of HttpRequestHandler (which is invoked by HttpRequestHandlerAdapter strategy, registered by default). We can also use a Controller implementation instead, in that case we will intend to use SimpleControllerHandlerAdapter strategy (also registered by default). Check out HandlerAdapter tutorial to get familiar with the concept.
Implementing HttpRequestHandler
public class MyHttpRequestHandler implements HttpRequestHandler {
@Override
public void handleRequest (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.write("response from MyHttpRequestHandler, uri: "+request.getRequestURI());
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
Example ProjectDependencies and Technologies Used: - spring-webmvc 4.3.9.RELEASE: Spring Web MVC.
- javax.servlet-api 3.0.1 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|