Spring MVC Complete Example

Source: Internet
Author: User

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.

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 major papers involved.

The dependency jar package required by the importer. As shown in.

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.

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"ID= "webapp_id" version= "2.5" > <display-name>springmvc_employee</display-name> <!--the front control Ler of ThisSpring WEB Application, responsible forhandling all application requests-<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframew Ork.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextconf Iglocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> < ;/init-param> <load-on-startup>1</load-on-startup> </servlet><!--Map all requests to the Dispatcherservlet forHandling--<servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url -pattern> </servlet-mapping></web-app>

Spring-servlet.xml (You can also use the Applicationcontext.xml file)

<?xml version= "1.0" encoding= "UTF-8"? ><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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsd"><context:component-scanbase-package= "Com.franson"></context:component-scan> <!--Configure the Internalresourceviewresolver--<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" id= "Internalresource Viewresolver > <!--prefixes--<property name= "prefix" value= "/web-inf/views/"/> <!-- suffix--<property name= "suffix" value= ". jsp"/> </bean></beans>

Employeecontroller.java

 PackageCom.franson.controller;ImportJavax.annotation.Resource;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportCom.franson.service.EmployeeService; @Controller @requestmapping (Value= "Employee") Public classEmployeecontroller {@Resource employeeservice employeeservice; @RequestMapping (Value= "GetAll", method=requestmethod.get) PublicString GetAllEmployees (model model) {Model.addattribute ("Employees", Employeeservice.getallemployees ()); return"EmployeeList"; }}

Model Employee.java

 PackageCom.franson.model; Public classEmployee {PrivateString Dept; Private intID; PrivateString name;  PublicString getdept () {returnDept; }     Public intgetId () {returnID; }     PublicString GetName () {returnname; }     Public voidsetdept (String dept) { This. Dept =Dept; }     Public voidSetId (intID) { This. ID =ID; }     Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"Employee [dept=" + dept + ", id=" + ID + ", name=" + name + "]"; }}

Iemployeedao.java

This class is located in the third tier of the three-tier architecture. Responsible for interacting with the underlying database store.

 Package Com.franson.dao; Import java.util.List; Import Com.franson.model.Employee;  Public Interface Iemployeedao {    List<Employee> getallemployees ();}

Employeedao.java

 PackageCom.franson.dao;Importjava.util.ArrayList;Importjava.util.List;Importorg.springframework.stereotype.Repository;ImportCom.franson.model.Employee; @Repository (Value= "Defaultemployeedao") Public classEmployeeDAOImplementsIemployeedao {@Override PublicList<employee>getallemployees () {List<Employee> lstemployees =NewArraylist<employee>(); Employee P1=NewEmployee (); P1.setid (1); P1.setname ("Franson"); P1.setdept ("Three"); Employee P2=NewEmployee (); P2.setid (2); P2.setname ("Lily"); P2.setdept ("A"); Employee P3=NewEmployee (); P3.setid (3); P3.setname ("Tom"); P3.setdept ("Two"); Employee P4=NewEmployee (); P4.setid (4); P4.setname ("Liao"); P4.setdept ("Five");        Lstemployees.add (p1);        Lstemployees.add (p2);        Lstemployees.add (p3);        Lstemployees.add (p4); returnlstemployees; }}

Iemployeeservice.java

This class is in the second tier of the three-tier architecture. Responsible for interacting with the DAO layer.

 Package Com.franson.service; Import java.util.List; Import Com.franson.model.Employee;  Public Interface Iemployeeservice {List<Employee> getallemployees ();}

The specific implementation classes are as follows:

 PackageCom.franson.service;Importjava.util.List;ImportJavax.annotation.Resource;ImportOrg.springframework.stereotype.Service;ImportCom.franson.dao.IEmployeeDao;ImportCom.franson.model.Employee; @Service Public classEmployeeServiceImplementsIemployeeservice {@Resource (name= "Defaultemployeedao") Iemployeedao EmployeeDAO; @Override PublicList<employee>getallemployees () {returnemployeedao.getallemployees (); }}

Employeeslist.jsp (for use with bootstrap)

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "Import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><%@ taglib Prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>href= "Https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >class= "Container" > <divclass= "Row" > <tableclass= "Table table-striped" > <tr> <th>ID</th> <th& gt; user name </th> <th> Department </th> </tr> <c:foreach ite                        ms= "${employees}" var= "employ" > <tr> <td>${employ.id}</td>                    <td>${employ.name}</td> <td>${employ.dept}</td>     </tr> </c:forEach> </table> </div> </div> <script src= "//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"/> <script src= "Https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"/></body>

Deployed in the Tomcat6 container, enter the address in the browser:http://localhost:8080/springmvc_employee/mvcemployee/all

You can see the results as shown:

Spring MVC Complete Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.