Spring MVC BeanNameViewResolver example

1. Introduction

In Spring RESTful Web Service applications, when we are concerned about returning a JSON response. We have already learnt how to create a RESTful Web Service application in our previous article. Particularly with older Spring versions (< 3.2), where there is no support for @RestController  or ResponseEntity, BeanNameViewResolver and @ResponseBody are still there for our rescue. In this article we will check out how we can configure BeanNameViewResolver and use it for our Spring RESTful Web Service application.

2. Implementation

There is slight change in configuration that basically involves the dispatcher servlet XML, where we need to define the ViewResolver bean for BeanNameViewResolver and another bean for the ViewClass, most importantly with the name attribute, to process the model returned from the controller to the respective view format based on the ViewClass bean, which in our case is a JSON.

The viewName returned from the controller should be the same as the bean name we have defined for the View.

Let’s take a look at the highlighted lines in our application’s web application context –


mvc-dispatcher-servlet.xml

The ViewResolver provides a mapping between view names and actual views. This means that the view name returned from the controller is processed and resolved to the actual view after consultation with the defined ViewResolver, which in our case is the BeanNameViewResolverBeanNameViewResolver is a ViewResolver implementation that resolves the view name returned from the controller as a bean name registered in the application context. This further means that if the controller returns the view name as jsonView, BeanNameViewResolver invokes the corresponding View implementation bean named as jsonView and resolves/parses the model object into the corresponding View Type (JSP, Velocity, Thymeleaf) or format (JSON, XML).

Next is how our Controller would look like.

EmployeeController.java

Useful Links:

3. Download the source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.