Home  >  Spring MVC

Spring MVC UrlBasedViewResolver Example with Java Configuration

By Arvind Rai, April 03, 2015
In this page we will learn Spring MVC UrlBasedViewResolver example with java configuration. UrlBasedViewResolver is the implementation of ViewResolver interface. It works on the basis of symbolic view name. When a method in controller class redirects to a page, it helps to find out the actual file path. Find some methods of UrlBasedViewResolver.
setPrefix(): Append a prefix with the value returned by Controller method.
setSuffix(): Append a suffix with the value returned by Controller method.
setViewClass(): Sets view class like JstlView.class.
setCache(): We pass true/false to enable/disable caching.
Now find a code snippet.
resolver.setPrefix("/views/");  
resolver.setSuffix(".jsp"); 
Suppose a method in controller class returns result string, then the view name will be
/views/result.jsp .
Find the complete example.


Project Structure in Eclipse

Find the project structure in eclipse.
Spring MVC UrlBasedViewResolver Example  with Java Configuration

Configuration Class using UrlBasedViewResolver

Find the java configuration file for UrlBasedViewResolver.
AppConfig.java
package com.concretepage.config;  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration 
@ComponentScan("com.concretepage") 
public class AppConfig {  
	@Bean  
        public UrlBasedViewResolver urlBasedViewResolver() {  
          UrlBasedViewResolver resolver = new UrlBasedViewResolver();  
          resolver.setPrefix("/views/");  
          resolver.setSuffix(".jsp");
          resolver.setCache(false);
          resolver.setViewClass(JstlView.class);  
          return resolver;  
        }
} 

Create Controller

Find the controller used in demo.
WelcomeController.java
package com.concretepage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/myworld")
public class WelcomeController {
	@RequestMapping("/welcome")
        public String hello(Model model) {
	    model.addAttribute("msg", "UrlBasedViewResolver Demo");
            return "success";
	}
} 

Create JSP Page

Find the JSP page.
success.jsp
<html>
<head>
<title>Spring MVC</title>
</head>
	<body>
	<h1>${msg}</h1>
	</body>
</html> 

Output

Run the URL
http://localhost:8080/concretepage-1/myworld/welcome
Output will be as given below.
Spring MVC UrlBasedViewResolver Example  with Java Configuration

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us