Spring MVC tutorial (I) Spring MVC overview, Spring MVC tutorial Overview

Source: Internet
Author: User
Tags file url spring mvc tutorial

Spring MVC tutorial (I) Spring MVC overview, Spring MVC tutorial Overview

Spring MVCThe Framework is an open-source Java platform that provides comprehensive infrastructure support for developing powerful Java-based Web applications very easily and quickly.

Spring web MVCThe framework provides the MVC (Model-View-Controller) architecture and components for developing flexible and loosely coupled Web applications.MVCMode separates different aspects of the application (input logic, business logic, and UI logic) and provides loose coupling between these elements.

  • Model)Encapsulated application data, usuallyPOJOClass.
  • View)Rendering model data. Generally, it generates a client browser that can interpret HTML output.
  • Controller)Responsible for processing user requests, building appropriate models, and passing them to the view for rendering.
DispatcherServlet component class

Spring WebThe Model-View-controller (MVC) framework is centered aroundDispatcherServletDesigned to process all HTTP requests and responses.Spring Web MVC DispatcherServletShows the request processing workflow:


The following areDispatcherServletThe sequence of incoming HTTP requests:

  • After receiving an HTTP request,DispatcherServletQueryHandlerMappingTo call the correspondingController.
  • ControllerAccept the request andGETOrPOSTMethod to call the corresponding service method. The service method sets the model data based on the defined business logic and returns the view nameDispatcherServlet.
  • DispatcherServletToViewResolverObtain the request definition view.
  • When the view is complete,DispatcherServletPass the model data to the final view and render it in the browser.

All of the above components, namely:HandlerMapping,ControllerAndViewResolverYesWebApplicationContextIs a commonApplicationContextWith some additional features required by Web applications.

Required Configuration

Useweb.xmlFile URL ing to map the desiredDispatcherServletThe request to be processed. The following is an example to showHelloWeb DispatcherServletSample description and ing:

 1 <web-app id="WebApp_ID" version="2.4" 2     xmlns="http://java.sun.com/xml/ns/j2ee"  3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  5     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 6  7     <display-name>Spring MVC Application</display-name> 8  9    <servlet>10       <servlet-name>HelloWeb</servlet-name>11       <servlet-class>12          org.springframework.web.servlet.DispatcherServlet13       </servlet-class>14       <load-on-startup>1</load-on-startup>15    </servlet>16 17    <servlet-mapping>18       <servlet-name>HelloWeb</servlet-name>19       <url-pattern>*.jsp</url-pattern>20    </servlet-mapping>21 22 </web-app>

web.xmlThe file will saveWebContent/WEB-INFDirectory. InHelloWeb DispatcherServletDuring initialization, the framework will tryWebContent/WEB-INFName in the directory[servlet-name]-servlet.xmlTo load the application context. In this example, the file used isHelloWeb-servlet.xml.

Next,<servlet-mapping>Mark to indicate whichURLDispatcherServletProcessing. All.jspAll HTTP requests endHelloWeb DispatcherServletProcessing.

If you do not want to use the default file name[servlet-name]-servlet.xmlAnd the default location isWebContent/WEB-INF, You canweb.xmlFileservletListenerContextLoaderListenerCustomize the file name and location as follows:

 1 <web-app...> 2  3 <!-------- DispatcherServlet definition goes here-----> 4 .... 5 <context-param> 6    <param-name>contextConfigLocation</param-name> 7    <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> 8 </context-param> 9 10 <listener>11    <listener-class>12       org.springframework.web.context.ContextLoaderListener13    </listener-class>14 </listener>15 </web-app>


Now let's take a lookHelloWeb-servlet.xmlFile must be configured in the Web ApplicationWebContent/WEB-INFDirectory:

 1 <beans xmlns="http://www.springframework.org/schema/beans" 2    xmlns:context="http://www.springframework.org/schema/context" 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4    xsi:schemaLocation=" 5    http://www.springframework.org/schema/beans      6    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 7    http://www.springframework.org/schema/context  8    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 9 10    <context:component-scan base-package="com.yiibai" />11 12    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">13       <property name="prefix" value="/WEB-INF/jsp/" />14       <property name="suffix" value=".jsp" />15    </bean>16 17 </beans>


See the followingHelloWeb-servlet.xmlFile highlights:

  • [servlet-name]-servlet.xmlFile will be used to create the definedbeanIt will overwrite any definition using the same name in the global scopebean.

  • <context:component-scan ...>Tags will be used for activationSpring MVCAnnotation scanning function, which can be used@ControllerAnd@RequestMapping.

  • InternalResourceViewResolverDefine rules used to parse view names. According to the rule defined above,helloThe logical view/WEB-INF/jsp/hello.jspThis view is implemented.

The next section describes how to create an actual component. That is, the Controller, model, and view.

Define Controller

DispatcherServletDelegates the request to the Controller to perform its specific functions.@ControllerAnnotation indicates the role of a specific class as a controller.@RequestMappingAnnotations are used to map URLs to the entire class or specific handler methods.

 1 @Controller 2 @RequestMapping("/hello") 3 public class HelloController{ 4  5    @RequestMapping(method = RequestMethod.GET) 6    public String printHello(ModelMap model) { 7       model.addAttribute("message", "Hello Spring MVC Framework!"); 8       return "hello"; 9    }10 11 }

@ControllerAnnotation defines the classSpring MVCController. Here@RequestMappingThe first usage/helloPath. Next comment@RequestMapping(method = RequestMethod.GET)Used to declareprintHello()Method is the default service method of the Controller to process http get requests. Another method can be defined to process the sameURLAny POST request.

It can be written in the Controller above in another form@RequestMappingAdd other attributes, as shown below:

 1 @Controller 2 public class HelloController{ 3  4    @RequestMapping(value = "/hello", method = RequestMethod.GET) 5    public String printHello(ModelMap model) { 6       model.addAttribute("message", "Hello Spring MVC Framework!"); 7       return "hello"; 8    } 9 10 }

valueProperty indicates the URL mapped to by the handler method,methodAttribute defines the service method used to process http get requests. For the Controller defined above, pay attention to the following points:

  • Define the required business logic in the service method. You can call other methods in this method as needed.
  • A model is created in this method based on the defined business logic. You can set different model attributes. These attributes are accessed by the view to display the final result. This example is created with the property"message.
  • The defined service method can returnStringIt contains the name of the view to be used to render the model. In this example,helloThe logical view name is returned.
Create a JSP View

Spring MVCMultiple types of views are supported for different representation technologies. Including-JSP, HTML, PDF, Excel worksheet, XML, Velocity template, XSLT, JSON, Atom and RSS source, JasperReports, etc. However, the most common JSP template is JSPL. the JSP template is used here, and/WEB-INF/hello/hello.jspWrite a simplehelloView:


Here${message}YesController. Multiple attributes can be displayed in the view.

Related Article

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.