Introduction to Spring MVC

Source: Internet
Author: User

I. Introduction to Spring WEB MVC
spring Web MVC is a Java-based lightweight web framework that implements the request-driven type of the Web MVC design pattern, that is, the idea of using the MVC architecture pattern, Decoupling the WEB layer from responsibility, and based on the request-driven, is the use of the request-response model, which is designed to help us simplify development, and Spring Web MVC simplifies our daily web development.
two, Spring Web MVC Advantage
1, Clear role partitioning: front-end controller (dispatcherservlet), request-to-processor mapping (handlermapping), processor adapter (handleradapter), view resolver (viewresolver), The processor or page controller (Controller), authenticator (   Validator), Command object (the object that the command  request parameter is bound to is called the Command object), the form object The object that is provided for presentation and submission to the form is called a Form object.
2, the Division of labor is clear, and the extension point is quite flexible, can easily expand, although almost no need;
3. Because the command object is a Pojo, you can use the command object directly as a business object without inheriting the framework-specific API,
4, and the other spring frameworks seamlessly integrate is not available in other web frameworks;
5, adaptable, can support any class as a processor through Handleradapter,
6, customizable, handlermapping, viewresolver, etc. can be very simple customization;
7, Powerful data validation, formatting, binding mechanism;
8, the use of spring-provided mock objects can be very simple web-level unit testing,
9, localization, the resolution of the theme of support, making it easier for us to switch between internationalization and theme.
10, a powerful JSP tag library, make JSP writing easier.
three, Spring Web MVC process Request Flow

1 The user sends a request to the front-end controller (dispatcherservlet) 2 front-end controller that requests a request to the page Controller/processor 3 processor to call the business object to process the request, and the business object processes the completion request to return the model data to the Processor 4 processor to get the Modelandview ( The model data and the attempted logical name are returned to the front controller 5 front-end controller to pass the model data to the view and render the View 6 front-end controller to retract control and respond the view to the user
Iv. Getting Started with Hello world
1, the front-end controller configuration
Add the following configuration in Web. xml:

Java code
    1. <servlet>    
    2.     <servlet-name >chapter2</servlet-name>    
    3.     <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet- class>    
    4.     <load-on-startup>1</LOAD-ON-STARTUP>&NBSP;&NBSP;&NBSP;&NBSP;
    5. </servlet>     
    6. <servlet-mapping>    
    7.     < servlet-name>chapter2</servlet-name>    
    8.     < url-pattern>/</url-pattern>    
    9. </servlet-mapping>     
<servlet> <servlet-name>chapter2</servlet-name> <servlet-clas S>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</      load-on-startup> </servlet> <servlet-mapping> <servlet-name>chapter2</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> 

Load-on-startup: Indicates that the servlet is initialized when the container is started, Url-pattern: Indicates which requests are given to spring Web MVC processing, and "/" is used to define the default servlet mappings. You can also block all requests that have HTML extensions as "*.html". Since this request has been given to the spring WEB MVC Framework, we need to configure the spring configuration file, and the default dispatcherservlet will load the Web-inf/[dispatcherservlet servlet name. Servlet.xml configuration file. This example is Web-inf/chapter2-servlet.xml.
2. Configure Handlermapping, Handleradapter in spring configuration file specific configuration in the Web-inf/chapter2-servlet.xml file

Java code
    1. <!--handlermapping--
    2. <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    3. <!--Handleradapter--
    4. <bean class="Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--handlermapping---  <bean class= " Org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping "/>     <!--handleradapter--  

Beannameurlhandlermapping: Represents the URL of the request and the Bean name Mapping, such as the URL is "context/hello", the spring configuration file must have a bean named "/hello", the context is ignored by default. Simplecontrollerhandleradapter: Indicates that all beans that implement the Org.springframework.web.servlet.mvc.Controller interface can act as spring web The processor in MVC. If other types of processors are required, they can be resolved by implementing hadleradapter.
3. Configure the Viewresolver in the spring configuration file
Specific configuration in the Web-inf/chapter2-servlet.xml file:

Java code
    1. <!-- viewresolver -->    
    2. <bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >    
    3.     <property name= "Viewclass"  value= " Org.springframework.web.servlet.view.JstlView "/>&NBSP;&NBSP;&NBSP;&NBSP;
    4.      <property name= "prefix"  value= "/web-inf/jsp /"/>&NBSP;&NBSP;&NBSP;&NBSP;
    5.     <property name= "suffix"  value= ". jsp"/>&NBSP;&NBSP;&NBSP;&NBSP;
    6. </bean>    
<!--viewresolver--<bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" viewclass "value=" Org.springframework.web.servlet.view.JstlView "/> <property name=" prefix "value="/web-inf/jsp/"/> <PR Operty name= "suffix" value= ". jsp"/> </bean> 

Internalresourceviewresolver: Used to support servlet, JSP View resolution, Viewclass:jstlview means JSP template page need to use JSTL tag library, The classpath must contain JSTL related jar packages, prefix and suffix: find the prefix and suffix of the view page (prefix [logical view name] suffix), such as the logical view that is passed in named Hello, the JSP view page should be stored in the "web-inf/ Jsp/hello.jsp ";
4. Development Processor/Page Controller

Java code
  1. Package Cn.javass.chapter2.web.controller;
  2. Import Javax.servlet.http.HttpServletRequest;
  3. Import Javax.servlet.http.HttpServletResponse;
  4. Import Org.springframework.web.servlet.ModelAndView;
  5. Import Org.springframework.web.servlet.mvc.Controller;
  6. Public class Helloworldcontroller implements Controller {
  7. @Override
  8. Public Modelandview HandleRequest (httpservletrequest req, HttpServletResponse resp) throws Exception {
  9. ///1, collect parameters, verify parameters
  10. ///2, binding parameters to the Command object
  11. ///3, incoming command object to business object for business processing
  12. //4, select the next page
  13. Modelandview mv = new Modelandview ();
  14. //Add model data can be any Pojo object
  15. Mv.addobject ("message", "Hello world!");
  16. //Set the logical view name, and the view resolver resolves to the specific view page based on that name
  17. Mv.setviewname ("Hello");
  18. return MV;
  19. }
  20. }
package Cn.javass.chapter2.web.controller;  Import Javax.servlet.http.HttpServletRequest;  Import Javax.servlet.http.HttpServletResponse;  Import Org.springframework.web.servlet.ModelAndView;  Import Org.springframework.web.servlet.mvc.Controller; public class Helloworldcontroller implements Controller {@Override public modelandview handlerequest (httpservle Trequest req, HttpServletResponse resp) throws Exception {///1, collecting parameters, validating parameters//2, binding parameters to command object//3, passing command objects to         Business object for Business processing//4, select Next page modelandview mv = new Modelandview ();         Add model data can be any Pojo object Mv.addobject ("message", "Hello world!");         Sets the logical view name, and the view resolver resolves to the specific view page mv.setviewname ("Hello") based on that name;      return MV; }  }  

org.springframework.we B.servlet.mvc.controller: the page Controller/processor must implement the Controller interface, be careful not to choose the wrong, we will learn the other way to implement the processor, public Modelandview handlerequest ( HttpServletRequest req, HttpServletResponse resp): function processing method, to achieve the corresponding function processing, such as collecting parameters, validating parameters, binding parameters to the Command object, the command object into the business object for business processing, Finally, the Modelandview object is returned; Modelandview: contains the model data and the logical view name to be implemented by the view; "Mv.addobject (" message "," Hello world! "); "represents the addition of model data, which can be any Pojo object;" Mv.setviewname ("Hello"); " Indicates that the set logical view is named "Hello", and the view resolver resolves it to a specific view, such as the view parser in front of Internalresourcevi. Wresolver will parse it as "web-inf/jsp/hello.jsp".
We need to add it to the Spring configuration file (Web-inf/chapter2-servlet.xml) to accept the spring IOC container management:

Java code
    1. <!--processor--
    2. <bean name="/hello" class="Cn.javass.chapter2.web.controller.HelloWorldController"/>
<!--processors--  <bean name= "/hello" class= "Cn.javass.chapter2.web.controller.HelloWorldController"/>  

Name= "/hello": the beannameurlhandlermapping configured in front of it, indicating that if the requested URL is "context/hello", it will be handed over to the bean for processing.
5. Development View Page To Create a/web-inf/jsp/hello.jsp view page:

Java code
  1. <%@ page language="java" contenttype="text/html; Charset=utf-8 "pageencoding="UTF-8 "%>
  2. <! DOCTYPE HTML public "-//W3C//DTD HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > " /c3>
  3. <meta http-equiv="Content-type" content= "text/html; Charset=utf-8 ">
  4. <title>hello world</title>
  5. <body>
  6. ${message}
  7. </body>
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>  <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  

${message} : Represents the display of model data transmitted by the Helloworldcontroller processor.
By Request: Http://localhost:9080/springmvc-chapter2/hello, if the page output "Hello world! "It shows that we have succeeded!"
Five, Spring MVC core Development steps:

1,   Dispatcherservlet deployment description in Web. XML, which intercepts the request to spring Web MVC

3,   Handleradapter configuration to support multiple types of processors

5, the Processor (page controller) configuration, so as to perform functional processing

Introduction to Spring MVC

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.