Flat Preloader Icon

Spring MVC Multiple View

  • In a Spring MVC application, you can easily handle multiple views by creating multiple controllers and corresponding views. Each controller is responsible for handling a specific URL and rendering a specific view.
  • Here’s how to set up multiple views in a Spring MVC application:

Step 1: Create Multiple Controllers

  • Create separate controller classes for each view you want to handle. Each controller should be annotated with @Controller and define methods to handle specific URLs.
				
					@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "home"; 
        // Return the view name 
        (e.g., home.jsp)
    }
}

@Controller
public class AboutController {
    @GetMapping("/about")
    public String about() {
        return "about"; 
        // Return the view name 
        (e.g., about.jsp)
    }
}

				
			

Step 2: Create Multiple JSP Views

  • For each controller, create corresponding JSP views in the src/main/webapp/WEB-INF/views directory. Name the views according to the view name returned by the controllers.
  • For example, if the HomeController returns “home,” create a home.jsp file. If the AboutController returns “about,” create an about.jsp file.
Here’s an example of a home.jsp:
				
					<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h1>Welcome to the Home Page</h1>
</body>
</html>

				
			
				
					<!DOCTYPE html>
<html>
<head>
    <title>About Page</title>
</head>
<body>
    <h1>About Us</h1>
    <p>We are a company that
    does amazing things.</p>
</body>
</html>

				
			

Step 3: Configure View Resolver

  • In your Spring MVC configuration (e.g., dispatcher-servlet.xml), configure the view resolver to resolve view names to JSP files.
				
					<bean class="org.springframework
.web.servlet.view
.InternalResourceViewResolver">
    <property name="prefix" 
    value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

				
			

Step 4: Access Multiple Views

  • Now, you can access the multiple views by navigating to the corresponding URLs defined in your controllers:
    • To access the home page, visit http://localhost:8080/your-web-app-context/.
    • To access the about page, visit http://localhost:8080/your-web-app-context/about.