Spring MVC - BeanNameViewResolver Example

[Updated: Sep 2, 2017, Created: Sep 1, 2017]

BeanNameViewResolver maps a view name to a bean name in the current application context. The matching bean must implement the View interface so that it can be executed by DispatcherServlet to render the view.

Example

A custom view

public class MyCustomView implements View {

  @Override
  public String getContentType() {
      return "text/html";
  }

  @Override
  public void render(Map<String, ?> model, HttpServletRequest request,
                     HttpServletResponse response) throws Exception {
      response.setContentType(getContentType());
      PrintWriter writer = response.getWriter();
      writer.println("This is my custom dummy view.<br/>");
      writer.println("<h3>Model attributes</h3>");
      for (Map.Entry<String, ?> entry : model.entrySet()) {
          writer.printf("%s = %s<br/>", entry.getKey(), entry.getValue());
      }
  }
}

Registering BeanNameViewResolver and the view as Bean

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig {

  @Bean
  public ViewResolver viewResolver() {
      return new BeanNameViewResolver();
  }

  @Bean("simpleView")
  public View myCustomView() {
      return new MyCustomView();
  }
}

Alternative way to register BeanNameViewResolver

As an alternative to above configuration, we can enable BeanNameViewResolver by overriding configureViewResolvers() method of WebMvcConfigurerAdapter:

public class MyWebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureViewResolvers (ViewResolverRegistry registry) {
        registry.beanName();
    }

    @Bean("simpleView")
    public View myCustomView() {
        return new MyCustomView();
    }
}

Writing a Controller

The controller that is going to return our bean name as the view name.

@Controller
@RequestMapping("/")
public class MyController {
  
  @RequestMapping
  public String handleRequest (Model model) {
      model.addAttribute("msg", "A message from the controller");
      model.addAttribute("time", LocalTime.now());
      return "simpleView";
  }
}

Output

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 4.3.10.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

BeanNameViewResolver Example Select All Download
  • bean-view-resolver-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also