Last Updated on 20 June 2019   |   Print Email
Normally in Spring MVC, we specify view names in handler methods of a controller class. For example:
@RequestMapping("/")
public String visitHome() {
return "home";
}
This handler method returns a logical view named home. What if we want to change this view name after deployment without touching the source code and re-compiling the project? Spring provides the ParameterizableViewController class which is used for parameterizing view name in configuration file instead of writing hard-coded view name in the handler method.Typically, a ParameterizableViewController bean should be used in conjunction with a view resolver (e.g. InternalResourceViewResolver) and a URL handler mapping (e.g. SimpleUrlHandlerMapping). Let’s see a couple of examples.
1. ParameterizableViewController with XML Configuration
Firstly, declare a view resolver as following code snippet:
As you can see, this bean defines the value “home” for the view name. This name can be changed when needed without re-compiling code, hence the parameterization.Thirdly, we need to declare a URL handler mapping which makes a certain URL pattern to be handled by a controller - the ParameterizableViewControllerin this case. Here’s the XML code:
The ParameterizableViewControllerclass also has a statusCodeproperty which can be useful when you want to return a specific HTTP status code for the matching URL. For example:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments