Spring MVC Example

Facebooktwitterredditpinterestlinkedinmailby feather

Spring MVC Example

We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC.

Following are the steps used to create an example of Spring MVC:

Step 1: Add the following maven dependencies into pom.xml or download the Spring jar files.

pom.xml

Step 2:  Create a web request page index.jsp that contains two links.

index.jsp

Step 3: Create a Controller class with the name MainController. In the controller class we have used two annotations: @Controller and @RequestMapping.

  • @Controller: The annotation @Controller is used to indicate a class as a “Controller.”
  • @RequestMapping: The annotation @RequestMapping is used to map the HTTP requests to handler methods of MVC.

MainController.java

Step 4: Add the entry of the Controller into web.xml. In the web.xml file, we are going to declare one Servlet (DispatcherServlet) to receive web requests. 

web.xml

Step 5: Add the entry of bean into different XML (spring-servlet.xml) file. We can give any name to the bean xml file.In the spring-servlet.xml file, we are going to use the view resolver with the view component. The InternalResourceViewResolver class is used for the view resolver.

spring-servlet.xml

Step 6: Create JSP files that we have used in the controller class. We have used homepage.jsp and about.jsp pages.

homepage.jsp

Step 7: Run the project on server.

Output

Run the project on server.

When we click on the Home page, it returns the following response.

When we click on the Home page,

When we click on the About Us, it returns the following response.

When we click on the About Us

Directory Structure of Spring MVC example

The following image shows the directory structure of Spring MVC.

Directory Structure of Spring MVC example
Facebooktwitterredditpinterestlinkedinmailby feather