- 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.
Home Page
Welcome to the Home Page
About Page
About Us
We are a company that
does amazing things.
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.
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.