"Springmvc Learning 05" Summary of parameter binding in SPRINGMVC--------------to add the same length to other people's parameter bindings

Source: Internet
Author: User

 As we all know, SPRINGMVC is used to process a page of some requests, and then return the data through the view back to the user, the previous few posts are used in the static data, in order to get a quick start Springmvc, in this blog post, I will summarize the parameters of how to receive the foreground page in Springmvc, that is, the parameter binding problem in SPRINGMVC.

This recommendation does not knock the code just to see because it can not be well connected to the previous article;

1. Process of parameter binding

  We can recall that in struts2, a member variable is defined in the action to receive the parameters passed in by the foreground, whereas in Springmvc, the data submitted by the receiving page is received through a method parameter. From the Key/value data requested by the client, the parameters are bound, the Key/value data is bound to the parameters of the Controller method, and then the parameter can be used in the controller. Take a look at this process:

  So we know that SPRINGMVC provides a lot of converters to bind page parameters to the parameter of the Controller method, and I'll refer to the custom converter. After a general understanding of the process, let's start with a concrete summary.

2. Default Supported Types

  SPRINGMVC, there is a supported default type of binding. That is, you can use these objects by defining objects of the default type directly on the controller method parameters.

  1. HttpServletRequest Object
  2. HttpServletResponse Object
  3. HttpSession Object
  4. Model/modelmap Object

  During parameter binding, binding is done directly if the type above is encountered. That is, we can define these types of parameters directly in the parameter of the controller's method, and SPRINGMVC will automatically bind. Here to illustrate is the Model/modelmap object, model is an interface, MODELMAP is an interface implementation, the role is to populate the model data to the request domain, similar to Modelandview, about its use, I'm going to say it with the simple type parameter bindings below.

3. Simple type of binding

  To summarize this or take the demand as an example, it is easier to understand, assuming there is a need: according to the product ID to modify the corresponding point of the product information. So the front page must pass in the ID of the product, and then SPRINGMVC the controller for processing, returning a page to modify the product information. About the front page of the things are very simple, I do not post code, the main section of the figure, the specific code at the end of the article.
  The foreground page passes the parameters through the URL, and the request is edititems.action.

the Edititems method in the controller is written below: @RequestMapping ("/edititems")  Public throws Exception {    // according to ID query corresponding items    itemscustom itemscustom =  Itemsservice.finditemsbyid (ID);    Model.addattribute ("Itemscustom", Itemscustom);     // The model data is passed to the    page through the model in the formal parameter // equivalent to the Modelandview.addobject method    return "/web-inf/jsp/items/edititems.jsp";}

  This is a very simple demo, as you can see from the code above that the model can be directly used as a parameter, SPRINGMVC binds it by default, and then uses the model to put the queried data into the request domain so that the data can be taken out of the foreground page.
  It is important to note that in a simple type of binding, the parameter names in the method parameters must be the same as the name passed in by the foreground to complete the binding of the arguments. Then someone asked, if there is a special need (such as better readability?). ), the name of the parameter defined here is not the same, then what is the whole? Is there a way out? Yes! We can use annotation @requestparam to bind a simple type to a parameter, as follows:

  Therefore, if you do not use @requestparam, request the parameter name passed in and the Controller method has the same formal parameter name before binding succeeds. If you use @requestparam, you do not have to restrict the request to pass in parameter names consistent with the Controller method's formal parameter names. The Required property in @requestparam Specifies whether the parameter must be passed in, and if set to True, an error will be given without an incoming parameter.

4. Binding of the Pojo type 4.1 Common Pojo types

  Again to summarize the Pojo type of binding, continue the above case, when the page shows the product details, I made the changes, and then click Submit, the background should be my submitted parameters are all updated to the database in the items table, that is, The parameters that I submit are bound to the items object or to its extension object. Let's take a look at the properties in items:

  As you can see, there are various types of attributes, and when we commit, we want to encapsulate all these properties in a pojo and then go to update the database.
  Binding is simple, for basic types, you can bind data in a page to Pojo by requiring the Name property value of the input tag in the page to be the same as the property names in the controller's Pojo parameter. That is, the foreground page is passed in the name of the Pojo property to be encapsulated exactly the same name, and then you can put the Pojo as a formal parameter in the controller's method, as follows:

  This allows you to encapsulate the different attribute values in the foreground table only son into the itemscustom. But run it will find an error, error message is unable to convert the string type to Java.util.Date type, because there is a property in the above items is a date type of createtime. This requires that we define the converter ourselves, which is the focus of this section, and we define a date converter ourselves:

//need to implement the converter interface, here is the conversion of string type to date type Public classCustomdateconverterImplementsConverter<string, date>{@Override PublicDate Convert (String source) {//implement convert date string to date type (format is YYYY-MM-DD HH:mm:ss)SimpleDateFormat SimpleDateFormat =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Try {            //turn directly back            returnsimpledateformat.parse (source); } Catch(ParseException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        //If parameter binding fails, returns null        return NULL; }}

  Once the converter is defined, the following configuration is required in Springmvc.xml:


  Now, SPRINGMVC can convert the string type to the date type correctly based on the converter, and then encapsulate it into the itemscustom.
  Here is a small episode: After modifying the product details submitted, there may be a Chinese garbled problem, expression submission is post mode, Springmvc about the post method of Chinese garbled problem can be configured in Web. XML in a filter to solve, as follows:

4.2. Pojo Type of packaging

  What is the difference between this packing type Pojo and the ordinary Pojo above? Packaging type Pojo refers to the Pojo has another is also pojo properties, that is Pojo set Pojo, why design this pojo? As I mentioned in the previous blog post, this combination of design methods is useful for later program extensions, such as complex query conditions that need to be packaged into this type of wrapper.
  So how do you bind it? There are two ways of thinking:

  1. Add the HttpServletRequest request parameter to the formal parameter to receive the query condition parameters through request.
  2. In the formal parameter, let the Pojo of the wrapper type receive the query condition parameter.

  The first approach is similar to the original servlet, where the second method is used, and we pass in a wrapper type of Pojo. Take a look at the Pojo of this package type:

  There is also a Itemscustom class in this wrapper Pojo, which inherits the items class and is used to extend related information in the user object related to items. So this itemscustom has the name attribute, what if we want to encapsulate the Name property passed in by the foreground into the name attribute in Itemscustom? This is the Pojo parameter binding problem for the wrapper type.
  Very simple, at the front desk we can pass this way:

  Then the controller in the method of the formal parameters of the package type of Pojo, that is, Itemsqueryvo, hit a breakpoint, you can see whether the value is passed in. As follows:

  This can be based on the user passed in the parameters, the replication of the query operation.

5. Binding of collection types 5.1 Binding of arrays

  The binding of arrays means that there are multiple data of the same type in the foreground, and we use array parameters in the controller to receive data from the foreground. Or a case to drive this part of the content, such as now we want to bulk delete goods, then we need to tick a few products, these products have ID number, in the controller, we need to get all these ID numbers and put into an array, The corresponding item in the database is then deleted by the ID number in the array. So how do you bind it? In fact, it is very simple, as follows:
  The controller's method is defined as:

  The parameters that correspond to the foreground pass are:

  This allows you to bind multiple IDs passed in from the foreground to the array, and then we can get the ID of the item to delete from the array.

binding of the 5.2 list

  Usually when you need to submit data in bulk, the data will be submitted to the binding list<pojo> , such as: score input (input multi-course results, batch submission), here we assume that there is demand: bulk product modification, enter multiple product information on the page, to submit multiple product information to the Controller method, Update multiple product information at once.
  So the idea is to add a new one in the extension class Itemsqueryvo List<ItemsCustom> , and then save the information for the different items to the list, so modify the following:

  Definition of the Controller method:

1, enter the bulk product modification page
2. Batch modification of product submission

  So there should be two methods in the controller, as follows:

  How does the foreground JSP page pass in the parameters? This is the problem we care about, because the data received in the background parameter is the wrapper class Itemsqueryvo. See below:

 So we know that the foreground is passing parameters in a form similar to List[i].name. List[i] denotes the first itemscustom and then List[i]. The property represents the corresponding attribute in the I-itemscustom.

Bindings for 5.2 map

  The binding of the map is actually the same as the binding of the list, and the first is to add a new map type attribute to the Pojo of the wrapper, such as (I would like to give an example, regardless of this example)

class Queryvo {privatenew hashmap<string, student>();   // Get/set method:}

The key is that the foreground is not the same as the list when the reference, such as map is transmitted, such as:

<TR>    <TD>Student Information:</TD>    <TD>Name:<inputtype= "text"name= "iteminfo[' name ']"/>Age:<inputtype= "text"name= "iteminfo[' price ']"/>    .. .. .. </TD></TR>

We can see that the parameter bindings for map come from the key in the map, and then value is automatically bound to the attribute of that object in the map. In the controller of the method, the formal parameters are directly used to receive QUERYVO, but also very simple.
  About SPRINGMVC parameter binding basically summed up to this, in fact, the principle is similar, just for different types, binding way some difference, think more about writing, basic can master these.

"Springmvc Learning 05" Summary of parameter binding in SPRINGMVC--------------to add the same length to other people's parameter bindings

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.