Getting Started with Spring MVC
1.1. What is Spring Web mvc?
Spring Web MVC is a lightweight web framework that implements the request-driven type of the Web MVC design pattern based on Java, that is, the idea of using the MVC architecture pattern, decoupling the WEB layer from responsibility, and based on the request-driven approach is to use the request-response model, The purpose of the framework is to help us simplify our development, and Spring Web MVC also simplifies our daily web development.
1.2. What Spring Web MVC can do for us
√ allows us to design a clean web layer and a thin web layer very simply;
√ The development of a more concise web layer;
√ Natural integration with spring framework (e.g. IOC container, AOP, etc.);
√ Provide a strong contract with more than the configuration of the contractual programming support;
√ Simple unit testing of the Web layer;
√ Support flexible URL to page controller mapping;
√ It is very easy to integrate with other view technologies, such as velocity, freemarker, and so on, because the model data is not placed in a particular API, but in a model (map data structure is implemented so it is easily used by other frameworks);
√ Very flexible data validation, formatting and data binding mechanism, can use any object for data binding, do not need to implement a specific framework of the API;
√ Provide a powerful set of JSP tag libraries to simplify JSP development;
√ Support flexible localization, theme and other analysis;
√ More simple exception handling;
√ Support for static resources;
√ Support restful style.
1.3. Spring WEB MVC Architecture
The Spring Web MVC Framework is also a request-driven web framework that is designed with a front-end controller pattern and then distributed to the appropriate page controller (action/processor) based on the request mapping rules. First let's look at the process of Spring WEB MVC processing requests as a whole:
The following steps are performed:
1, the first user to send the request ———— > Front-end controller, the front-end controller according to the request information (such as URL) to decide which page controller to process and delegate the request to it, that is, the control logic of the previous controller, 1, 2 steps in the diagram;
2, after the page controller receives the request, carries on the function processing, first needs to collect and binds the request parameter to an object, this object calls the Command object in spring Web MVC, validates, and then delegates the command object to the business object for processing ; Returns a modelandview (model data and Logical view name) after processing; 3, 4, 5 steps in the diagram;
3, the front controller retract control, and then according to the return of the logical view name, select the corresponding view to render, and the model data passed in so that the view rendering; steps 6, 7 in the figure;
4, the front controller again regain control, return the response to the user, the figure of step 8; This concludes the whole.
1.4. Hello World Introduction
1.4.1, preparing the development environment and operating environment:
☆ Engineering: Dynamic Web Engineering (SPRINGMVC)
☆spring Framework Download:
Spring-framework-3.1.1.release-with-docs.zip
☆ Dependent JAR Package:
1. Spring Framework jar Package:
For simplicity, copy all jar packages under spring-framework-3.1.1.release-with-docs.zip/dist/to the Web-inf/lib directory of the project;
2. The spring framework depends on the jar package:
Apache Commons logging logs need to be added, Commons.logging-1.1.1.jar is used here;
Need to add JSTL tag library support, used here are Jstl-1.1.2.jar and Standard-1.1.2.jar;
1.4.2, front-end controller configuration
In our web. XML, add the following configuration:
<servlet> <Servlet-name>Chapter2</Servlet-name> <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class> <!--Load-on-startup: Indicates initialization of the servlet when the container is started - <Load-on-startup>1</Load-on-startup> </servlet> <servlet-mapping> <Servlet-name>Chapter2</Servlet-name> <!--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". - <Url-pattern>/</Url-pattern> </servlet-mapping>
Load-on-startup: Indicates that the servlet was initialized when the container was 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.
1.4.3, configure handlermapping in the spring configuration file, handleradapter specific configuration in the Web-inf/chapter2-servlet.xml file:
<!--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. - <Beanclass= "Org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!--indicates that all beans that implement the Org.springframework.web.servlet.mvc.Controller interface can act as a processor in spring Web MVC. If other types of processors are required, they can be resolved by implementing hadleradapter. - <Beanclass= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
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.
1.4.4, configuring Viewresolver in the Spring configuration file
Specific configuration in the Web-inf/chapter2-servlet.xml file:
<!--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 incoming logical view named Hello, the JSP view page should be stored in the "web-inf/jsp /hello.jsp "; - <Beanclass= "Org.springframework.web.servlet.view.InternalResourceViewResolver"> < Propertyname= "Viewclass"value= "Org.springframework.web.servlet.view.JstlView" /> < Propertyname= "prefix"value= "/web-inf/jsp/" /> < Propertyname= "suffix"value= ". jsp" /> </Bean>
Internalresourceviewresolver: Used to support servlet, JSP view parsing;
Viewclass:jstlview indicates that the JSP template page needs to use the JSTL tag library, the classpath must contain the relevant jar package of JSTL;
Prefix and suffix: find the prefix and suffix of the view page (prefix [logical view name] suffix), such as the incoming logical view named Hello, then the JSP view page should be stored in "web-inf/jsp/hello.jsp";
1.4.5, Development Processor/Page Controller
PackageCOM.TEST.LJQ;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.web.servlet.ModelAndView;ImportOrg.springframework.web.servlet.mvc.Controller;/*** Page Controller * *@authorLin Yi-chin *@version1.0 2013-11-1 pm 05:39:25*/ Public classHelloworldcontrollerImplementsController {//Org.springframework.web.servlet.mvc.Controller: The page Controller/processor must implement the Controller interface, take care not to choose the wrong, behind we will learn other processor implementation methods;//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, passing the command object to the business object for business processing, and finally returning the Modelandview object;//Modelandview: Contains the model data and logical view names to be implemented by the view, for example://"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. Resolver 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: PublicModelandview HandleRequest (httpservletrequest arg0, HttpServletResponse arg1)throwsException {//1. Collect parameters and verify parameters//2. Binding parameters to the Command object//3, the Command object incoming business object for business processing//4. Select the next pageModelandview mv =NewModelandview (); //add model data, which can be any of the Pojo objectsMv.addobject ("message", "Hello world!"); //sets the logical view name that the view resolver resolves to a specific view page based on that nameMv.setviewname ("Hello"); returnMV; }}
Org.springframework.web.servlet.mvc.Controller: the page Controller/processor must implement the Controller interface, take care not to choose the wrong, behind we will learn other processor implementation methods;
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, passing the command object to the business object for business processing, and finally returning the Modelandview object;
Modelandview: Contains the model data and logical view names 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:
<!--- < name = "/hello" Class = "Com.test.ljq.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.
1.4.6, Development View page
To create a/web-inf/jsp/hello.jsp view page:
<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><%@ taglib URI="Http://java.sun.com/jsp/jstl/core"prefix="C"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML> <Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"> <title>Insert Title here</title> </Head> <Body>${message}</Body></HTML>
${message}: Represents the display of model data sent by the Helloworldcontroller processor.
1.4.7, starting the server to run the test
By request: Http://localhost:8083/springmvc/hello, if the page output "Hello world! "It shows that we have succeeded!"
Getting Started with Spring MVC