In this example, we will build an entry-level Web application using the Spring MVC framework. Spring MVC is one of the most important modules of the spring framework. It is based on a powerful spring IOC container and makes full use of the container's characteristics to simplify its configuration.
Directory
- What is the MVC framework
- Dispatcher Servlet (Spring Controller)
- Spring Getting Started sample
- Run-time dependent libraries
- Web. XML and Spring-servlet.xml file configuration
- Request Controller Employeecontroller.java
- View Model Employeevo.java
- DAO class
- Business Layer Classes
- View employeelistdisplay.jsp
What is the MVC framework
Model-View-Controller (MVC) is a well-known design pattern based on the design of the interface application . It decouples the business logic from the interface primarily by separating the models, views, and roles of the controller in the application. Typically, the model is responsible for encapsulating application data in the view layer presentation. The view simply shows the data and does not contain any business logic. The controller is responsible for receiving requests from the user and invoking the background service (Manager or DAO) to process the business logic. After processing, the background business layer may return some data to be presented at the view level. The controller collects this data and prepares the model for presentation at the view level. The core idea of the MVC pattern is to separate the business logic from the interface, allowing them to change independently without affecting each other.
In spring MVC applications, models are typically composed of Pojo objects, which are processed in the business layer and persisted in the persistence layer. Views are typically JSP templates written in the JSP Standard Tag library (JSTL). The controller section is the responsibility of the dispatcher servlet, and in this tutorial we will learn more about its details.
Some developers believe that the business layer and DAO layer classes are part of the MVC model component. I have a different opinion on this. I don't think the business layer and DAO layer classes are part of the MVC framework. Typically a Web application is a 3-tier architecture, the data-business-representation. MVC is actually part of the presentation layer.
Dispatcher Servlet (Spring Controller)
In the simplest spring MVC application, the controller is the only servlet that you need to configure in the Java Web Deployment description file (that is, the. xml file). The Spring MVC controller-often called the dispatcher Servlet-implements the front-end controller design pattern. And each Web request must pass through it so that it can manage the lifetime of the entire request.
When a Web request is sent to a spring MVC application, the dispatcher servlet first receives the request. It then organizes the components that are configured in the Spring Web application context (such as the actual request processing controller and the view resolver) or configured with annotations, all of which require processing of the request.
Define a controller class in Spring3.0, this class must be labeled with @controller annotations. When a controller with @controller annotations receives a request, it looks for a suitable handler method to handle the request. This requires the controller to map each request to the handler method through one or more handler mappings. To do so, the method of a controller class needs to be decorated with @requestmapping annotations, making them the handler method.
When the handler method finishes processing the request, it delegates control to the view with the same view name as the handler method return value. To provide a flexible approach, the return value of a handler method does not represent a view implementation but a logical view that does not have any file name extensions. You can map these logical views to the correct implementation and write these implementations to the context file so that you can easily change the view layer code without even modifying the code of the request handler class.
Matching the correct file for a logical name is the responsibility of the view resolver. Once the controller class has resolved a view name to a view implementation. It renders the corresponding object according to the design that the view implements.
Spring Getting Started sample
In this application, I will create a demo of the simplest employee management application , which has only one feature, the list of all employees that the system provides. Let's write down the directory structure for this application.
Now let's write all the files that involve this starter application.
Pom.xml
The following pom.xml files contain the spring MVC dependency and the taglib dependency that supports writing JSP files
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.howtodoinjava.demo</groupId> <artifactId> Springmvcexample</artifactid> <packaging>war</packaging> <version>1.0-snapshot</ version> <name>springmvcexample Maven webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactid& Gt;junit</artifactid> <version>4.12</version> <scope>test</scope> </dependency> <!--Spring MVC Support---<dependency> <GROUPID>ORG.SP Ringframework</groupid> <artifactid>sPring-webmvc</artifactid> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <ARTIFACTID>SPRING-WEB&L T;/artifactid> <version>4.1.4.RELEASE</version> </dependency> <!--Tag Li BS support for View Layer-<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtim e</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <scope >runtime</scope> </dependency> </dependencies> <build> <FINALNAME>SPR Ingmvcexample</finalnAme> </build></project>
Xml
This most streamlined Web. xml file declares a servlet (that is, the dispatcher servlet) to receive all types of requests. The Dispatcher servlet acts as a front-end controller here.
<web-app id= "webapp_id" version= "2.4" xmlns= "http://java.sun.com/xml/ns/j2ee" xmlns:xsi= "/http/ Www.w3.org/2001/XMLSchema-instance " xsi:schemalocation=" http://java.sun.com/xml/ns/j2eehttp://java.sun.com /xml/ns/j2ee/web-app_2_4.xsd "> <display-name>spring Web MVC Hello World application</display-name > <servlet> <servlet-name>spring</servlet-name> <servlet-class> Org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1< /load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</ servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>
Spring-servlet.xml (You can also use the Applicationcontext.xml file)
In requesting handler, the business layer, the DAO layer, we use annotated classes, so I enabled annotation handling for all classes in the "Com.howtodoinjava.demo" package
<web-app id= "webapp_id" version= "2.4" xmlns= "http://java.sun.com/xml/ns/j2ee" xmlns:xsi= "/http/ Www.w3.org/2001/XMLSchema-instance " xsi:schemalocation=" http://java.sun.com/xml/ns/j2eehttp://java.sun.com /xml/ns/j2ee/web-app_2_4.xsd "> <display-name>spring Web MVC Hello World application</display-name > <servlet> <servlet-name>spring</servlet-name> <servlet-class> Org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</ load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</ servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>
Employeecontroller.java
Annotation @requestmapping determines the URL of the method to be called at the class level and method level level.
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:context=" Http://www.springframework.org/schema/context "xsi:schemalocation="/HTTP/ www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp:// Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd " > <context:component-scan base-package= "Com.howtodoinjava.demo"/> <bean class= "Org.springframework.web . servlet.mvc.annotation.DefaultAnnotationHandlerMapping "/> <bean class=" Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "/> <bean class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf /views/"/> <property name=" suffix "value=". jsp "/> </bean></beans>
Read more: How do I use @component, @Respository, @Service, and @controller annotations?
Employeevo.java
This class acts as a model of the MVC pattern.
Package Com.howtodoinjava.demo.model;import Java.io.serializable;public class Employeevo implements serializable{ private static final long serialversionuid = 1L; Private Integer ID; Private String firstName; Private String lastName; Setters and Getters @Override public String toString () { return "Employeevo [id=" + ID + ", firstname=" + fi Rstname + ", lastname=" + LastName + "]";} }
Employeedao.java
This class is located in the third tier of the three-tier architecture. Responsible for interacting with the underlying database store.
Import Java.util.list;import Com.howtodoinjava.demo.model.employeevo;public interface employeedao{public List <EmployeeVO> getallemployees ();}
Employeedaoimpl.java
Import Java.util.arraylist;import Java.util.list;import Org.springframework.stereotype.repository;import Com.howtodoinjava.demo.model.EmployeeVO; @Repositorypublic class Employeedaoimpl implements EmployeeDAO {public List<employeevo> getallemployees () { list<employeevo> employees = new Arraylist<employeevo > (); Employeevo vo1 = new Employeevo (); Vo1.setid (1); Vo1.setfirstname ("Lokesh"); Vo1.setlastname ("Gupta"); Employees.add (VO1); Employeevo VO2 = new Employeevo (); Vo2.setid (2); Vo2.setfirstname ("Raj"); Vo2.setlastname ("Kishore"); Employees.add (VO2); return employees;} }
Employeemanager.java
This class is in the second tier of the three-tier architecture. Responsible for interacting with the DAO layer.
Import Java.util.list;import Com.howtodoinjava.demo.model.employeevo;public interface employeemanager{public List<employeevo> getallemployees ();}
Employeemanagerimpl.java
Import Java.util.list;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Com.howtodoinjava.demo.dao.employeedao;import Com.howtodoinjava.demo.model.EmployeeVO, @Servicepublic class Employeemanagerimpl implements Employeemanager { @ autowired EmployeeDAO DAO; Public list<employeevo> getallemployees () { return dao.getallemployees (); }}
employeeslistdisplay.jsp
This JSP is used to display all employees in the system. It loops through the employee collection and prints their details in a table. This conforms to the MVC pattern of the view layer.
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"% ><%@ taglib prefix= "FMT" uri= "http://java.sun.com/jsp/jstl/fmt"%>
Now deploy the application on your application server (I'm using Tomcat 7). and click "Http://localhost:8080/springmvcexample/employee-module/getAllEmployees". If you've configured everything correctly, you'll see it under the screen:
Spring MVC builds an entry-level WEB application