Spring MVC Learning Note 1

Source: Internet
Author: User

I. Building spring MVC's Hello World

1. Add a jar package:

Commons-logging-1.1.1.jar

Spring-aop-4.1.6.release.jar

Spring-beans-4.1.6.release.jar

Spring-context-4.1.6.release.jar

Spring-core-4.1.6.release.jar

Spring-expression-4.1.6.release.jar

Spring-web-4.1.6.release.jar

Spring-webmvc-4.1.6.release.jar

At least 8 of these.

2. Configure the interception servlet in Web. xml:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" Http://xmlns.jcp.org/xml/ns/javaee/http Xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "version=" 3.1 "> <!--configuration Dispatcherservlet--&LT;SERVL Et> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframe Work.web.servlet.dispatcherservlet</servlet-class> <!--Configure an initialization parameter for the Dispatcherservlet: Configure the bits of the SPRINGMVC configuration file Place and name-<init-param> <param-name>contextConfigLocation</param-name> &lt ;p aram-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1< /load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet< /servlet-name> <url-pattErn>/</url-pattern> </servlet-mapping></web-app> 
which

<!--Configure an initialization parameter for the Dispatcherservlet: Configure the location and name of the SPRINGMVC configuration file--        <init-param>            <param-name> Contextconfiglocation</param-name>            <param-value>classpath:springmvc.xml</param-value>        </init-param>
Used to describe the address of the configuration file, the Spring.xml file under SRC, the name of this file can be defined by itself.

3. Write Spring.xml configuration 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" Xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/ Context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/ Schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <!--Configure custom scanned Packages--<context: Component-scan base-package= "Com.springmvc"/> <!--configuration prefix and suffix--<bean class= "        Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/"/> <property name= "suffix" value= ". jsp"/> </bean></beans>

There are two main properties that need to be configured, one is the controller controllers package, which is used for scanning. There is also a resource is a diagram parser, used to generate the view file location, and the directory is the Web directory.

The corresponding JSP is: Prefix + return string + suffix suffix.

4. Write the control class code, return success, corresponding to the Web directory under the success.jsp file:

@Controllerpublic class HelloWorld {    @RequestMapping ("/hello") public    String Hello () {        System.out.print ( "Hello World");        Return "Success";    }}


Process: URL request--dispatcherservlet intercept--Find the scan package based on the sprig profile--Find the controller--Find the method--Get the return value--according to the stitching to get the corresponding view--display



Two. Use of various annotations:

1. Note @controller: Placed on the class to indicate that the class is a controller.


2. Note @requestmapping: Request mappings, resolve URLs, determine methods in the requested class and class:

1. @RequestMapping In addition to the modification method, you can also modify the class, if the class definition is not labeled @RequestMapping, then the URL tag at the method is relative to the WEB app's root directory

2.1). Class definition: A concept similar to package.

2). Method: Provides further subdivision mapping information. Relative to the URL at the class definition.

3. You can use the method property to specify the request mode so that only the post submission executes

/**     * Common: Use the Method property to specify the request method     *    /@RequestMapping (value = "Testrequestmappingpostmethod", method = requestmethod.post) Public    String Testrequestmappingpostmethod () {        System.out.print (" Testrequestmappingpostmethod ");        return SUCCESS;    }

4. The params and headers properties are also used to further confirm the mapping relationship, which has the Requerid property to determine if it must have:

/**     * Understanding: You can use params and headers to map requests more precisely. Params and headers support simple expressions.     *    /@RequestMapping (value = "Testparams", params = {"username", "password"}) public    String testparams ()        { System.out.print ("Testparams");        return SUCCESS;    }

@RequestMapping (value = "Testparamsandheaders", params = {"username", "age!=10"}, headers = {"ACCEPT-LANGUAGE=EN-US,ZH; q=0.8 "}) public String testparamsandheaders () {System.out.println (" testparamsandheaders "); return SUCCESS;}

3. Note @pathvariable: The value used to get the placeholder, you can map the placeholders in the URL to the parameters of the target method:

    /**     * @PathVariable can be used to map placeholders in URLs to parameters in the target method.     */    @RequestMapping (value = "Testpathvariable/{id}") Public    String testpathvariable (@PathVariable ("id") Integer ID) {        System.out.print ("testpathvariable" + ID);        return SUCCESS;    }


The requested link is:

<a href= "/test/testpathvariable/121" >testPathVariable</a>
121 will be in the parameter ID.

4. Annotation @requestparam: Used to get the passed arguments.

The requested link:

<a href= "/test/testrequestparams?username=zhulei&password=123456" >testRequestParams</a>

Code to process:

/**     * @RequestParam to map the request parameters. Value is the parameter name of the request parameter required whether the parameter must be. Default is True     *               defaultvalue The default value of the request parameter *     /    @RequestMapping (value = "Testrequestparams") public    String Testrequestparams (@RequestParam (value = " Username ") string username, @RequestParam (value =" password ", required = False) string password) {        System.out.println ("username =" + username + ";" + "password =" + password);        return SUCCESS;    }

Add this annotation to the parameter of the method, and the corresponding parameter will be the one passed.


5. Note @requestparam: Some information used to get the header in the request:

/**     * Understanding: Mapping request header information usage with @RequestParam     *    /@RequestMapping (value = "Testrequestheader") public    String Testrequestheader (@RequestHeader (value = "Accept-language") String info) {        System.out.println ("Accept-language = "+ info");        return SUCCESS;    }

Here, is to get to the HTTP protocol, the request header of the Accept-language field information, and @requestparam usage, is to get the information of the head


Three. Common Request method parameter aspects

1. Note @cookievalue: Get the information in Coolie:

/**     * Learn:     *     * @CookieValue: Maps a Cookie value. Property with @RequestParam     *    /@RequestMapping (value = " Testcookievalue ") Public    string Testcookievalue (@CookieValue (value =" Jsessionid ") string id) {        System.out.println ("Jsessionid =" + ID);        return SUCCESS;    }

2. Similar to the 5th annotation @requestparam, you can directly encapsulate the information of the form into an object to obtain, and this is the same as struts2 interaction


Front desk form:

<form action= "/test/testpojo" >    username:<input type= "text" name= "username" ><br>    Password:<input type= "password" name= "password" ><br>    province:<input type= "text" Name= " Address.province "><br>    city:<input type=" text "name=" address.city "><br>    <input Type= "Submit" value= "Submit-put" ><br></form>

To process the class, accept the user information of the form, actually call the set method of the Pojo class and put it in the parameter user, support level two mapping:

/**     * Spring MVC automatically matches the requested parameter name and the POJO property name, and populates the property values for that object. Cascading properties are supported.     * such as: Dept.deptid, Dept.address.tel, etc. */    @RequestMapping (value = "Testpojo") public    String Testpojo ( User user) {        System.out.println (user.tostring ());        return SUCCESS;    }

3. You can use the Serlvet native API as a parameter of the target method to specifically support the following types

HttpServletRequest

HttpServletResponse

HttpSession

Java.security.Principal

Locale InputStream

OutputStream

Reader

Writer


Example:

@RequestMapping (value = "Testservletapi") public    String Testservletapi (httpservletrequest request, HttpServletResponse response, Writer out) throws IOException {        System.out.println (request.tostring () + ";" + Response.tostring ());        Out.write ("Hello");        return SUCCESS;    }

The native Servlet API classes are directly assigned to the request method as arguments, and the classes are given automatically.

This calls writer directly and writes a hello output.


Four. Working with data models

The third part is to get the data from the Web page to the Java request method, the method is to use methods parameters automatically assigned, this part is the processed data back to the page.


1. Using the Modelandview return type

    /**     * Processing data Model Modelandview *     /    /**     * The return value of the target method is the Modelandview type.     * This can include view and model information     * SPRINGMVC will put the data in the Modelandview model into the request domain object.     * @return     *    /@RequestMapping (value = "Testmodleandview") public    Modelandview Testmodleandview () {        String viewName = SUCCESS;        Modelandview Modelandview = new Modelandview (viewName);//        Fill data        modelandview.addobject ("date", new Date ());        return modelandview;    }

SPRINGMVC will put the data in the Modelandview model into the request domain object so that the foreground can get the values.

Front Code:

${requestscope.date}

2. Use map as the method parameter:

    /**     * Map of processing data Model */    /**     * Target method you can add parameters to the map type (which can actually be either the model type or the Modelmap type).     * @param map     * @return     *    /@RequestMapping (value = "TestMap") public    String TestMap (map<string, Object> map) {        map.put ("name", Arrays.aslist ("Tom", "Jerry", "Zhulei"));        return SUCCESS;    }

Similarly, SPRINGMVC will put the data in the map into the request domain object so that the foreground can get the values.


3. Use the annotation @sessionattributes to place the data in the session:


This annotation can only be placed above the class:

@SessionAttributes (value = {"User"}, types = {String.class})

There are two parameters that can be set, value and types.

Value is an array of strings that describe the method of the Controller class, and the name of the data that is placed in the request is also placed in the session, as long as it is well-defined.

Types is the type of the class that is defined, and the type of the class that is put in the request is defined and placed in the session.

    /**     * Processing data Model Sessionattributes *    //**     * @SessionAttributes except that you can specify the attributes that need to be placed in the session by the property name (in fact, the Value property is used ),     * You can also specify which model properties need to be placed into the session through the object type of the model property (actually using the types property value)     *     Note: This annotation can only be placed on top of the class. Instead of decorating the method.     *    /@RequestMapping (value = "Testsessionattribute") public    String Testsessionattribute (map<string, Object> map) {        User user = new User ();        User.setusername ("Zhulei");        User.setpassword ("123");        Map.put ("user", user);        Map.put ("string", "StringData");        return SUCCESS;    }




Spring MVC Learning Note 1

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.