Springmvc Detailed (v)------parameter binding

Source: Internet
Author: User
Tags dateformat wrapper

parameter binding, which simply means that the client sends the request, and the request contains some data, how does that data reach the Controller? This is the most used in the actual project development, then how is the SPRINGMVC parameter binding implemented? Let us explain in detail below.

1. SPRINGMVC parameter Binding

In Springmvc, the data that submits the request is received through a method parameter. The Key/value data that is requested from the client, is parameterized, binds the Key/value data to the controller's formal parameters, and then the controller can use the parameter directly.

  

Here is the parameter binding component, then what is the parameter component, which can be understood first to convert the requested data to the data we need is called the parameter binding component, that is, the parameter binding converter. SPRINGMVC has a number of parametric converters built in, and only in rare cases do we need to customize the parameter converters.

2. Default Supported Types

SPRINGMVC has a supported default parameter type, we can directly use these default types of declarations directly on the formal parameters. As follows:

①, HttpServletRequest objects

②, HttpServletResponse objects

③, HttpSession objects

④, Model/modelmap objects

Controller Code:

@RequestMapping ("/defaultparameter") public Modelandview Defaultparameter (HttpServletRequest request, HttpServletResponse response,httpsession Session,model model,modelmap modelmap) throws exception{ Request.setattribute ("Requestparameter", "Request Type"), Response.getwriter (). Write ("response"); Session.setattribute ("SessionParameter", "Session Type");//modelmap is an implementation class of the model interface that populates the model data with the request domain// Even with the model interface, the internal bindings are implemented by Modelmap Model.addattribute ("Modelparameter", "model Type"), Modelmap.addattribute (" Modelmapparameter "," Modelmap type "); Modelandview mv = new Modelandview (); Mv.setviewname ("view/success.jsp"); return MV;}

Form code: (Intercept main code)

<body>request:${requestparameter}session:${sessionparameter}model:${modelparameter}modelmap:${ Modelmapparameter}</body>

Then visit, the page appears as follows:

  

Here's the point. Model/modelmap,modelmap is an implementation class of the model interface that populates the model data into the request domain, even if the model interface is used, and its internal bindings are implemented by Modelmap

3. Binding of basic data types

What are the basic data types, we'll summarize here:

One, byte, occupies a byte, the value range is-128-127, the default is "\u0000", which means empty two, short, take up two bytes, the value range is 32768-32767 three, int, takes four bytes,- 2147483648-2147483647, long, occupies eight bytes, the long variable assignment must be added "L" or "L", otherwise it is not considered a long type five, float, take four bytes, the float type to assign value must be added "F" or "F", If not added, a compilation error is generated because it is automatically defined as a type double variable. Double conversion to float type data will lose precision. Float A = 12.23 generates a compilation error, float a = 12 is the correct six, double, take eight bytes, the double variable assignment is best when the "D" or "D", but not mandatory seven, Char, take two bytes, when defining the character type variable, To enclose in single quotation marks eight, Boolean, only two values "true" and "false", default value is False, cannot be replaced with 0 or non-zero, this is different from C language

Let's take the int type as an example:

JSP page Code:

<form action= "Basicdata" method= "POST" ><input name= "username" value= "ten" type= "text"/><input type= " Submit "Value=" ></form>

Controller Code:

@RequestMapping ("/basicdata") public void Basicdata (int username) {System.out.println (username);//10}

The result is a value that prints out the values of the form.

Note: The name value of input in the form is consistent with the controller's parameter variable name to complete the data binding. What if it's inconsistent? We use @RequestParam annotations to complete the following:

JSP page code unchanged, <input name= "username" > remain as is, Controller code is as follows

  

Using the annotation @RequestParam, we can use any parameter, but the value of the annotation is the same as the Name property value of the form.

Question: Our parameter here is the basic data type, if the value passed from the foreground page is null or "", then there will be data conversion exception, that is, must ensure that the table only son pass the data cannot be null or "", so, during the development process, the data may be empty, It is a good idea to define the parameter data type as a wrapper type, see the example below.

4. Binding of the wrapper data type

Package types such as Integer, Long, Byte, Double, Float, short, (String type is also applicable ) Here we take the integer as an example

The Controller code is:

  

Basically the same as the basic data type, except that the data passed by the table only son can be null or "", for example, if num in the form is "" or there is no num in the form input, then the NUM value in the Controller method parameter is null.

5. Binding of POJO (entity Class) type

User.java

Package Com.ys.po;import Java.util.date;public class User {    private Integer ID;    Private String username;    Private String sex;    Private Date birthday;    Public Integer getId () {        return ID;    }    public void SetId (Integer id) {        this.id = ID;    }    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        This.username = Username = = null? Null:username.trim ();    }    Public String Getsex () {        return sex;    }    public void Setsex (String sex) {        this.sex = sex = = null? Null:sex.trim ();    }    Public Date Getbirthday () {        return birthday;    }    public void Setbirthday (Date birthday) {        this.birthday = birthday;    }}

JSP page: Note the Name property value of the input box is consistent with the properties of the POJO entity class above to map successfully.

<form action= "Pojo" method= "POST" > User id:<input type= "text" name= "id" value= "2" ></br> User name: <input Type= "text" name= "username" value= "Marry" ></br> Gender: <input type= "text" name= "Sex" value= "female" ></br > Date of birth: <input type= "text" name= "Birthday" value= "2017-08-25" ></br><input type= "Submit" value= "Submit" ></form>

Note: Here we write the data are dead, directly submitted. There is an integer type, string type, of type date.

Controller:

@RequestMapping ("/pojo") public void Pojo (user user) {System.out.println (user);

We make a breakpoint in the code above and enter the URL to enter the controller:

The above is an error,User.java's Birthday property is a Date type, and we enter a string type, it is not binding

So the problem is, date type data binding failed, how to solve such a problem? That's what we said earlier. A converter that needs to customize the date type.

  ①, defining a converter of type string to Date

Package Com.ys.util;import Java.text.parseexception;import Java.text.simpledateformat;import java.util.Date;import The org.springframework.core.convert.converter.converter;//needs to implement the converter interface, where the string type is converted to the date type public class DateConverter implements Converter<string, date> {@Overridepublic date convert (string source) {//implementation converts a string to a date type ( Format is YYYY-MM-DD HH:mm:ss) SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); try {return Dateformat.parse (source);} catch (ParseException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Returns Nullreturn NULL if the parameter binding fails;}}

  ②, configuring the converter in the Springmvc.xml file

<mvc:annotation-driven conversion-service= "Conversionservice" ></mvc:annotation-driven><bean id= " Conversionservice "class=" Org.springframework.format.support.FormattingConversionServiceFactoryBean ">< Property name= "Converters" ><!--the class name of the custom converter--><bean class= "Com.ys.util.DateConverter" ></bean> </property></bean>

Enter the URL to view the controller's formal parameters again:

  

6. Binding of composite Pojo (entity Class) type

Here we add an entity class, Contactinfo.java

Package Com.ys.po;public class ContactInfo {    private Integer ID;    Private String Tel;    Private String address;    Public Integer getId () {        return ID;    }    public void SetId (Integer id) {        this.id = ID;    }    Public String Gettel () {        return tel;    }    public void Settel (String tel) {        This.tel = Tel = = null? Null:tel.trim ();    }    Public String getaddress () {        return address;    }    public void setaddress (String address) {        This.address = Address = = null? Null:address.trim ();    }}

Then add a property in the User.java above private ContactInfo ContactInfo

  

JSP page: Note the name of the property name, User.java the composite property names. Field name

      

Controller

  

The ContactInfo attribute is available in the user object, but in the form code, you need to use the property name (property of the object type). Name of the input.

7. Binding of array types

Requirements: We query all user information, and in the JSP page traversal display, at this time click the Submit button, you need to get the Controller in the page display the User class ID of all the values of the array collection.

JSP page: Note the name value of the user ID is defined as userId

  

Controller.java

  

8. Binding of List type

Requirements: Bulk modification of user users ' information

First step: Create Uservo.java, encapsulate list<user> properties

Package Com.ys.po;import Java.util.list;public class Uservo {private list<user> userlist;public list<user> Getuserlist () {return userlist;} public void Setuserlist (list<user> userlist) {this.userlist = userlist;}}

Second step: In order to simplify the process, we query the Controller directly from all User information, and then on the page display

Controller

@RequestMapping ("selectalluserandlist") public Modelandview selectalluserandlist () {list<user> Listuser = Userservice.selectalluser (); Modelandview mv = new Modelandview () mv.addobject ("Listuser", Listuser); Mv.setviewname ("list.jsp"); return MV;}

JSP page

Step three: After modifying the value of the page, click Submit

  

Since our Name property name in the JSP page input box definition is userlist[${status.index}].id, we can get the user information of the page batch submission directly with Uservo.

8. Binding of the map type

First add an attribute to the Uservo map<string,user> UserMap

Second step: JSP page, note the <input > Input Box Name property value

  

Step three: Get the properties of the page in the Controller

9. Problems encountered

①, form form cannot submit input inputs box property set to Disabled content

Like what:

<input type= "text" disabled= "disabled" name= "Metadataname"   maxlength= "" placeholder= "enter the model here in English name" title= " Model English name ""/>

Property with disabled= "disabled", after committing to controller, the value of Metadataname is null

Workaround: Change to readonly= "ReadOnly"

ReadOnly: Valid for input (Text/password) and textarea, when set to True, the user can get focus, but cannot edit, and when the form is submitted, the entry is submitted as the content of the form.

Disabled: For all form elements (Select,button,input,textarea, etc.), when set to Disabled is true, the form entry cannot have the focus, and all the user's actions are meaningless, when the form is submitted, The form entry is not submitted.

Springmvc Detailed (v)------parameter 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.