spring-Building MVC Project

Source: Internet
Author: User

SPRINGMVC is implemented based on the model-view-controller (MVC) pattern, which allows you to build loosely coupled web applications.

1. SPRINGMVC Request Process

1) request to leave the browser and carry the content requested by the user

2) The Dispatcherservlet role is the dispatcher (front controller). Querying one or more processor mappings to determine which controller handles the request

3) Send the request to the selected controller business processing

4) Once the controller is processed, the business data is encapsulated as a model and a logical view name is specified, which is returned to Dispatcherservlet

5) Dispatcherservlet to match the logical view name to a specific view implementation

6) render the specified view using the model data

7) Return to front end display

2, SPRINGMVC project configuration

Xml

<! DOCTYPE web-app Public "-//sun Microsystems, INC.//DTD Web application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3.dtd" >& Lt;web-app>  <!--<context-param>--> <!--<param-name>contextConfigLocation</param-name>--> <!--<param-value>classpath:applicationContext.xml</param-value>--> <!--</context-param >--> <!--<listener>--> <!--<listener-class>org.springframework.web.context.contextloa derlistener</listener-class>--> <!--</listener>--> <servlet> <servlet-name& Gt;appservlet</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</            Servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMvc.xml</param-value> </init-param> </servlet> <se Rvlet-mapping> <servlet-name>appServlet</servlet-name> &LT;URL-PATTERN&GT;/&LT;/URL-PATTERN&G    T </servlet-mapping></weB-app> 

Springmvc.xml

<?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/s Chema/context " xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:mvc="/HTTP/ Www.springframework.org/schema/mvc " xsi:schemalocation=" Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans.xsd   Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd/HTTP Www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--Scan Controller-- > <context:component-scan base-package= "Com.cn.controller" ></context:component-scan> <!--processor mapping- <mvc:annotation-driven></mvc:annotation-driven> <!--View Resolver-<bean class= "org.spring Framework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/jsp/"> </property> <property name= "suffix" value= ". jsp" ></property> </bean></beans>

3. Controller

How parameters are accepted

    • Query parameters
    • Form parameters
    • Path variable

Controller

PackageCom.cn.controller;ImportCom.cn.pojo.User;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.validation.Errors;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportJavax.validation.Valid; @ControllerPublicClassHellocontroller {@RequestMapping ("/Home")PublicString Home () {System.out.println ("Execute Home"));Return "Home";//Returns a string that is the logical view name} @RequestMapping ("/home2")PublicString home2 () {System.out.println ("Execute Home2");return "Redirect:home3";//A string containing redirect, indicating redirection to another processor;//If a string containing forward is moved to another processor} @RequestMapping ("/home3")PublicString Home3 () {System.out.println ("Output Home"));Return "Home3"; } @RequestMapping ("/show3")//form parameters, @Valid annotations are used with the user with the validation annotations addedPublicString ShowPerson3 (@Valid user user, Errors Errors) {//The errors parameter must follow the @valid parameterIf(Errors.haserrors ()) {//Check if there is a parameter System.out.println ("form element check does not pass"));Return "fail"; } System.out.println ("User information:" +user);Return "Success"; } @RequestMapping ("/{name}/{age}")//Path parameter http://localhost:8080/tt/123 output: Name: TT age: 123;;public String showPerson2 (@PathVariable (value = "name" age); return "Success" ;} @RequestMapping ("/show") // query parameter http://localhost:8080/show?name=pp&age=99 output: Name: PP Age: 99; ; public String Showperson (@RequestParam (value = "Name", defaultvalue = "Laowang" ) String name, @RequestParam (value = "Age", DefaultValue = "
                                                                        
                                                                         age); 
                                                                         return "Success"  "}}   
                                                                            

Pojo

PackageCom.cn.pojo;ImportCom.sun.istack.internal.NotNull;ImportJavax.validation.constraints.Size;PublicClassUser {Form parameter Check @NotNull @Size (min = 6,max = 10)PrivateString FirstName; @NotNull @Size (min = 6,max = 10)PrivateString LastName; @NotNull @Size (min = 6,max = 10)PrivateString name; @NotNull @Size (min = 6,max = 10)PrivateString passwd;PublicString Getfirstname () {ReturnFirstName; }PublicvoidSetfirstname (String firstName) {This.firstname =FirstName; }PublicString Getlastname () {ReturnLastName; }PublicvoidSetlastname (String lastName) {This.lastname =LastName; }PublicString GetName () {ReturnName }public void SetName ( String name {this.name = name;} public String getpasswd () {return passwd; } public void SETPASSWD ( String passwd) {this.passwd = passwd;} @Override public String toString () {return " user{"+" firstname= "+ firstName +" \ "+", lastname= ' + lastName + ' \ ' + ', name= ' + name + ' \ ' + ', passwd= ' "+ P asswd + ' \ ' + '} '            

4. View Parser

    • The string returned in the controller (which does not contain redirect, forward) represents the logical view name without invoking a specific view implementation. The Spring view parser can decide which view implementation to use to render the model. SPRINGMVC defines a viewresolver interface that is returned as a View object
 Public Interface viewresolver {    throws  Exception;}

View interface definition, where the Render method accepts the model, request, response parameter, and renders the model data to response

 Public Interface View {    = view.  Class. GetName () + ". ResponseStatus";     = View. class. GetName () + ". Pathvariables";     = View. class. GetName () + ". Selectedcontenttype";    String getContentType ();     void throws Exception;}
    • Implementation of the View parser

Spring provides viewresolver multiple built-in implementations, such as internalresourceviewresolver, Tilesviewresolver ... where Internalresourceviewresolver (the simplest and most commonly used view resolver ) resolves the view to the internal resources of the Web app (typically JSP)

    • Create a JSP view

Spring supports two types of JSP views---using internalresourceviewresolver

Method 1: Use the JSP standard Tag library (JSTL) in the page,internalresourceviewresolver can resolve the view name to the Jstlview form of the JSP file

Mode 2: Use the JSP tag library provided by spring (two: one for form-to-model binding; the other provides generic tool class features)

A. Configure the view resolver for JSP

class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name= "prefix "Value="/web-inf/jsp/"></property>      <property name=" suffix "value=". JSP "></property>< /bean>

The string returned in the controller is stitched together with the prefix in the configuration to complete the file path, and if the string returned in the controller contains a slash, a different directory can be distinguished. This configuration resolves the logical view name to a Internalresourceview instance.

If you use the JSTL tag to process content in a JSP, you want the view resolver to resolve the view to an Jstlview instance. Simply add a single line of configuration files:

class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >   <property Name= "Viewclass" value= "Org.springframework.web.servlet.view.JstlView" ></property>   < Property name= "prefix" value= "/web-inf/jsp/" ></property>   <property name= "suffix" value= ". jsp" > </property></bean>

B, spring's JSP tag library

...

spring-Building MVC Project

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.