Spring MVC - Mapping multiple URLs by using SimpleUrlHandlerMapping

[Updated: Jul 23, 2017, Created: Jun 26, 2017]

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.


Registering SimpleUrlHandlerMapping

SimpleUrlHandlerMapping is not registered by default, so we have to do that ourselves:

public class AppConfig {
  HttpRequestHandler httpRequestHandler () {
      return new MyHttpRequestHandler();
  public SimpleUrlHandlerMapping simpleUrlHandlerMapping () {
      SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
      Map<String, Object> map = new HashMap<>();
      map.put("/app/**", httpRequestHandler());
      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 {
  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


Example Project

Dependencies 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

Simple Url Handler Mapping Example Select All Download
  • simple-url-handler-mapping
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also