Autogenerated logical view name through RequestToViewNameTranslator

In this section, you will learn about handling the situation where view name is not provided, through RequestToViewNameTranslator interface.

Autogenerated logical view name through RequestToViewNameTranslator

Autogenerated logical view name through RequestToViewNameTranslator

In this section, you will learn about handling the situation where view name is not provided, through RequestToViewNameTranslator interface.

Where no view name is provided, the RequestToViewNameTranslator interface determines the view name automatically. For this you need to configure DefaultRequestToViewNameTranslator class in Spring MVC configuration file.

To understand it completely, lets take an example :

Consider the below controller code :

public class WritingController implements Controller {
	
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		// request processing 
		ModelAndView model= new ModelAndView(); // note that no view name is provided
		// addition of data as to the model
		return model;
	}
}

Note that no view name is provided in the above code. For auto generation of the view name, you need to configure the DefaultRequestToViewNameTranslator class in Spring MVC configuration file as shown below :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- this bean with the well known name generates view names for us -->
<bean id="viewNameTranslator"
class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/>

<bean class="x.y.WritingController">
<!-- inject dependencies as necessary -->
</bean>

<!-- maps request URLs to Controller names -->
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

</beans>

In the above controller code, you can see that no view name is provided. The DefaultRequestToViewNameTranslator class, configured in conjunction with ControllerClassNameHandlerMapping , is responsible for auto generating view name.

In the above case, if the requested URL is :

http://localhost/writing.html

the resultant generated logical view name would be writing .According to above configuration and returned view name the resultant view name would be reside in " /WEB-INF/jsp/ " as writing.jsp.