Spring MVC - Mapping a URL to a view without a controller

[Updated: Jul 23, 2017, Created: Feb 16, 2017]

In the last tutorial we understood the purpose of ViewControllerRegistry. In this example, we are going to use ViewControllerRegistry to map URL to view name along with a response status code. We will also see how to register a status code that will be returned with empty response body.

Mapping URL to view and setting status code

As we are going to use Spring boot, here's the main configuration class which is going to configure url to view mapping. We are also setting a status code:

@SpringBootApplication
public class Main extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers (ViewControllerRegistry registry) {
      ViewControllerRegistration r = registry.addViewController("/test");
      r.setViewName("myView");
      r.setStatusCode(HttpStatus.GONE);
  }

  public static void main (String[] args) {
      SpringApplication.run(Main.class, args);
  }
}

src/main/webapp/WEB-INF/pages/myView.jsp

<html>
  <body style="margin:20px;">
  JSP view
   <p>

   </p>
   <p>
      Response Status: <%=response.getStatus() %>
   </p>
  </body>
</html>

Boot's properties

src/main/resources/application.properties

spring.mvc.view.prefix= /WEB-INF/pages/
spring.mvc.view.suffix= .jsp

In this example we are not creating a controller as we don't need one to demostrate direct mapping of URL to view.

Running application:

mvn spring-boot:run

Output

Returning status code without a message body

In this case, we just have to specify a status code for a URL and no view name is needed. Spring will return the response with empty body.

@SpringBootApplication
public class Main extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers (ViewControllerRegistry registry) {
      registry.addStatusController("/test2", HttpStatus.SERVICE_UNAVAILABLE);
  }

  public static void main (String[] args) {
      SpringApplication.run(Main.class, args);
  }
}

Note that ViewControllerRegistry#addStatusController method return type is void, so it's simple one line of configuration.

Output

Using HTTPie

In the next tutorial, we are going to understand how to redirect a URL to another URL by using ViewControllerRegistry.

Example Project

Dependencies and Technologies Used :

  • spring-boot-starter-web 1.4.4.RELEASE: Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
    Corresponding Spring version: 4.3.6.RELEASE
  • tomcat-embed-jasper 8.5.11: Core Tomcat implementation.
  • JDK 1.8
  • Maven 3.3.9

Url View Direct Mapping Example Select All Download
  • url-view-mapping
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
        • webapp
          • WEB-INF
            • pages

See Also