Spring MVC Example
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
org.springframework spring-webmvc 5.1.8.RELEASE javax.servlet javax.servlet-api 4.0.0 provided
Step 2: Create a web request page index.jsp that contains two links.
index.jsp
Spring MVC Web application Home page | About Us
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
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { @RequestMapping("/home_page") public String showPage() { return "homepage" ; } @RequestMapping("/about_us") public String showPage2() { return "about" ; } }
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
springMVC dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring-servlet.xml 1 dispatcher /
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
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
Step 6: Create JSP files that we have used in the controller class. We have used homepage.jsp and about.jsp pages.
homepage.jsp
Home Page of Spring MVC
about.jsp
About Spring MVC Spring MVC is a web Model-View-Controller framework built on Servlet API which is used to build web applications.
Step 7: Run the project on server.
Output
When we click on the Home page, it returns the following response.
When we click on the About Us, it returns the following response.
Directory Structure of Spring MVC example
The following image shows the directory structure of Spring MVC.