SPRINGMVC Powerful Data binding

Source: Internet
Author: User
Tags locale

So far, the request has been handed over to our processor, and the next thing is to collect the data, and then we'll see what data we can collect from the request, 6-11:



Figure 6-11

1, @RequestParam binding order request parameter value;

2, @PathVariable bound URI template variable value;

3. @CookieValue Binding Cookie Data value

4, @RequestHeader binding request header data;

5, @ModelValue binding parameters to the command object;

6, @SessionAttributes Binding Command object to the session;

7, @RequestBody binding the requested content area data and can be automatic type conversion, and so on.

8, @RequestPart binding "Multipart/data" data, in addition to binding @requestparam can do the request parameters, but also to bind the uploaded files.

In addition to the annotations mentioned above, we can also get request data through APIs such as HttpServletRequest, but it is recommended to use annotations because it is easier to use.

Let's take a look at the parameter types supported by the function processing method.

6.6.1, function processing method supported parameter types

Before we go on, we need to first look at what types of formal parameters are supported by the function processing method, and what their specific meanings are.

first, servletrequest/httpservletrequest and Servletresponse/httpservletresponse

Java code
    1. Public String Requestorresponse (
    2. ServletRequest ServletRequest, HttpServletRequest httpservletrequest,
    3. Servletresponse Servletresponse, HttpServletResponse httpservletresponse
    4. )

The Spring Web MVC framework automatically helps us pass the corresponding servlet request/response (servlet API) as a parameter.

Ii. Inputstream/outputstream and Reader/writer

Java code
    1. public void Inputoroutbody (InputStream requestbodyin, OutputStream responsebodyout)
    2. Throws IOException {
    3. Responsebodyout.write ("Success". GetBytes ());
    4. }

Requestbodyin: Gets the content area byte stream of the request, equivalent to Request.getinputstream ();

Responsebodyout: Gets the corresponding content area byte stream, equivalent to Response.getoutputstream ().

Java code
    1. public void Readerorwritebody (reader reader, writer writer)
    2. Throws IOException {
    3. Writer.write ("Hello");
    4. }

Reader: Gets the content area character stream of the request, equivalent to Request.getreader ();

Writer: Gets the corresponding stream of content area characters, equivalent to Response.getwriter ().

Inputstream/outputstream and Reader/writer Two groups cannot be used at the same time, only one of these groups can be used.

Third, Webrequest/nativewebrequest

WebRequest is a unified request provider provided by spring WEB MVC that not only provides access to request-related data (such as parameter area data, request header data, but no cookie-area data), but also access to the data in the session and context ; Nativewebrequest inherits the WebRequest and provides a way to access the local servlet API.

Java code
  1. Public String webRequest (webRequest webRequest, nativewebrequest nativewebrequest) {
  2. System.out.println (Webrequest.getparameter ("Test"));//① gets the value of the request parameter test
  3. Webrequest.setattribute ("name", "value", webrequest.scope_request);//②
  4. System.out.println (Webrequest.getattribute ("name", Webrequest.scope_request));
  5. HttpServletRequest request =
  6. Nativewebrequest.getnativerequest (httpservletrequest.class);//③
  7. HttpServletResponse response =
  8. Nativewebrequest.getnativeresponse (Httpservletresponse.class);
  9. Return "Success";
  10. }

①webrequest.getparameter: Access the data of the request parameter area, can access the request header data through GetHeader ();

②webrequest.setattribute/getattribute: To fetch/drop attribute data within a specified scope, the three scopes defined by the servlet are represented by the following constants:

Scope_request: Representing the scope of the request;

Scope_session: Represents the session scope;

Scope_global_session: Represents the global session scope, which is the ServletContext context scope.

③nativewebrequest.getnativerequest/nativewebrequest.getnativeresponse: Get the local servlet API.

Iv. HttpSession

Java code
    1. Public String session (HttpSession session) {
    2. SYSTEM.OUT.PRINTLN (session);
    3. Return "Success";
    4. }

The session here is never null.

Note: Session access is not thread-safe, and if thread safety is required, A thread-safe access session is required to set the Synchronizeonsession property of Annotationmethodhandleradapter or Requestmappinghandleradapter to true.

V. Commands/Form objects

Spring Web MVC is able to automatically bind request parameters to the command/form object of the function handling method.

Java code
    1. @RequestMapping (value = "/commandobject", method = Requestmethod.get)
    2. Public String Tocreateuser (httpservletrequest request, Usermodel user) {
    3. return "Customer/create";
    4. }
    5. @RequestMapping (value = "/commandobject", method = Requestmethod.post)
    6. Public String CreateUser (httpservletrequest request, Usermodel user) {
    7. SYSTEM.OUT.PRINTLN (user);
    8. Return "Success";
    9. }

If a form is submitted (containing username and password text fields), the request parameter is automatically bound to the Command object user.

Vi. Model, Map, Modelmap

Spring Web MVC provides model, map, or modelmap so that we can expose the modeling data needed by the rendering view.

Java code
    1. @RequestMapping (value = "/model")
    2. Public String CreateUser (model model, Map Model2, Modelmap model3) {
    3. Model.addattribute ("A", "a");
    4. Model2.put ("B", "B");
    5. Model3.put ("C", "C");
    6. SYSTEM.OUT.PRINTLN (model = = MODEL2);
    7. System.out.println (Model2 = = MODEL3);
    8. Return "Success";}

Although there are three different types injected here (model, Map Model2, Modelmap model3), the three are the same object and 6-12 are as follows:



Figure 6-11

Annotationmethodhandleradapter and Requestmappinghandleradapter will use BINDINGAWAREMODELMAP as the implementation of the model object, where our formal parameters (model Model, Map Model2, Modelmap model3) are all the same bindingawaremodelmap instances.

Here is another point we need to take note:

Java code
    1. @RequestMapping (value = "/mergemodel")
    2. Public Modelandview Mergemodel (model model) {
    3. Model.addattribute ("A", "a");//① Add model data
    4. Modelandview mv = new Modelandview ("Success");
    5. Mv.addobject ("A", "Update");//② updating model data with the same name in ③ before view rendering
    6. Model.addattribute ("A", "new");//③ modify model data with the same name at ①
    7. A of the view page will be displayed as "update" instead of "new"
    8. return MV;
    9. }

From the code we can conclude that the model data in the return value of the function processing method (such as Modelandview) merges the model data in the function processing method parameters (such as models), but if there is a same name between the two, the model data in the return value overrides the model data in the formal parameter.

Seven, Errors/bindingresult

Java code
    1. @RequestMapping (value = "/error1")
    2. Public String Error1 (usermodel user, bindingresult result)

Java code
    1. @RequestMapping (value = "/error2")
    2. Public String Error2 (usermodel user, bindingresult result, model model) {

Java code
    1. @RequestMapping (value = "/error3")
    2. Public String Error3 (usermodel user, Errors Errors)

The above code can get the wrong object.

Before Spring3.1 (using Annotationmethodhandleradapter) The Error object must immediately follow the Command object/form object, as defined below:

Java code
    1. @RequestMapping (value = "/error4")
    2. Public String Error4 (Usermodel user, model model, Errors Errors)
    3. }

This is foolproof, as the above code starts with Spring3.1 (using Requestmappinghandleradapter), but it is recommended that "the wrong object immediately follows the Command object/Form Object".

For detailed use of errors and Bindingresult, refer to 4.16.2 data validation.

Viii. other Miscellaneous

Java code
    1. Public String Other (locale locale, Principal Principal)

Java.util.Locale: The localization information of the current request is obtained, the default equivalent to Servletrequest.getlocale (), if the configuration of the Localeresolver parser is determined by the Locale, followed by the introduction;

Java.security.Principal: The Principal object contains the user information passed by the validation, equivalent to Httpservletrequest.getuserprincipal ().

The above tests are in Cn.javass.chapter6.web.controller.paramtype.MethodParamTypeController.

The formal parameter types (such as httpentity, Uricomponentsbuilder, Sessionstatus, redirectattributes) of other functional processing methods are explained in detail in subsequent chapters.

The second chapter describes the data binding of the annotation method.

SPRINGMVC Powerful Data binding

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.