Spring Web MVC Framework
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files. The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features.
- Creating Spring Web MVC Application
Step 1: Open Eclipse > File > New > Dynamic Web Project.
Step 2: Set project name and select your target runtime as Apache Tomcat 7.0.
Step 3: Add below jar dependencies into WEB-INF/lib folder.
Step 4: Create Spring Configuration bean file into /WebContent/WEB-INF/ springDemo-servlet.xml.
This is the important configuration file where we need to specify the ViewResolver and View components.
Here, we defined a tag <context:component-scan>. It will allow Spring to load all the components from Package “com.spring.controller” and all its child package.
Also, we have to define bean viewResolver. we can provide view pages location through prefix and suffix properties. So, all our JSP pages should be in /WEB-INF/jsp/ directory.
Step 5: Create new file web.xml into /WebContent/WEB-INF/web.xml.
The above code in web.xml will map DispatcherServlet with URL pattern /welcome.jsp. Also note that we have define index.jsp as welcome file.
Step 6: Create controller classes.
- Right click on Java Resources -> src
- Click New -> Class
- Package: com.spring.controller
- Filename: HelloWorld.java
@Controller annotation is used to indicate that it’s a web controller class.
The helloWorld() method returns ModelAndView object. The ModelAndView object tries to resolve to a view named “welcome” and the data model is being passed back to the browser so we can access the data within the JSP. The logical view name will resolve to /WEB-INF/jsp/welcome.jsp
- Create new file into /WebContent/index.jspCreate new file into /WebContent/WEB-INF/jsp/welcome.jsp
Step 8: Run Spring Application
Right click on project -> run as -> run on server -> Select apache tomcat and click on finish.
When you click on above link, you will get below screen