SpringMVC (5) ------ parameter binding, springmvc ------

Source: Internet
Author: User
Tags dateformat

SpringMVC (5) ------ parameter binding, springmvc ------

To put it simply, when the client sends a request and the request contains some data, how does the data arrive at the Controller? This is also the most used in actual project development. How does SpringMVC parameter binding work? The following is a detailed explanation.

 

1. SpringMVC parameter binding

In SpringMVC, the data submitted for the request is received by using method parameters. From the key/value data requested by the client, after the parameter is bound, the key/value data is bound to the form parameter of the Controller, and then the form parameter can be directly used in the Controller.

  

The parameter binding component is involved here. What is the parameter component? Here we can first convert the request data to the required data called the parameter binding component, that is, the parameter binding converter. SpringMVC has many built-in parameter converters, which are customized only in rare cases.

 

2. Supported types by default

SpringMVC supports the default parameter types. We can directly use them by providing the declaration of these default types on the form parameters. As follows:

①. HttpServletRequest object

②. HttpServletResponse object

③ HttpSession object

④ Model/ModelMap object

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, which is used to fill the Model data into the request domain // even if the Model interface is used, the internal binding is implemented by ModelMap. addattrieter ("modelParameter", "model type"); modelMap. addattrieter ("modelMapParameter", "modelMap type"); ModelAndView mv = new ModelAndView (); mv. setViewName ("view/success. jsp "); return mv ;}

Form Code: (extract main code)

<body>request:${requestParameter}session:${sessionParameter}model:${modelParameter}modelMap:${modelMapParameter}</body>

Then, the page is displayed as follows:

  

Here we will focus on Model/ModelMap. ModelMap is an implementation class of the Model interface, which is used to fill the Model data into the request field, even if the Model interface is used, the internal binding is implemented by ModelMap.

 

3. Bind Basic Data Types

Which are the basic data types? Let's resummarize them here:

1. byte occupies one byte. The value range is-128-127. The default value is "\ u0000", which indicates null 2. short, which occupies two bytes, the value range is-32768-32767 3. int, which occupies four bytes.-2147483648-2147483647 4. long occupies eight bytes. You must add "L" or "l" when assigning values to long variables ", otherwise, it is not considered as long type 5 or float, which occupies four bytes. "F" or "f" must be added when assigning values to the float type. If it is not added, a compilation error will occur, because the system automatically defines it as a double variable. Converting double to float will result in loss of precision. Float a = 12.23 produces compilation errors. float a = 12 is correct. 6. double, which occupies eight bytes, when assigning values to double variables, it is best to add "D" or "d", but adding or not is not a hard rule 7. char, which occupies two bytes. when defining a double variable, it must be enclosed in single quotation marks (8) and boolean. There are only two values, "true" and "false". The default value is false. It cannot be replaced by 0 or not. This is different from the C language.

Take the int type as an example:

JSP page code:

<Form action = "basicData" method = "post"> <input name = "username" value = "10" type = "text"/> <input type = "submit" value = "Submit"> </form>

Controller code:

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

The result is the value of the value in the form.

Note: The name value of input in the form must be consistent with the name of the Controller parameter variable to complete data binding. So what if they are different? We use the @ RequestParam annotation to complete the process as follows:

The JSP page code remains unchanged. <input name = "username"> the Controller code is as follows:

  

Using annotation @ RequestParam, we can use any form parameter, but the value attribute value in the annotation must be the same as the name attribute value of the form.

 

Problem: Our parameter here is the basic data type. If the value passed from the foreground page is null or "", the data conversion exception will occur, it is necessary to ensure that the data transmitted from the form cannot be null or "". Therefore, during development, it is best to define the parameter data type as the packaging type for data that may be null, for more information, see the following example.

 

4. Bind The packaging Data Type

The packaging types include Integer, Long, Byte, Double, Float, and Short ,(The String type is also applicable.) Here we use Integer as an example.

Controller code:

  

Similar to the basic data type, the difference is that the data passed through the form can be null or "". The above code is used as an example, if the input value of num is "" in the form or the input value of num is not in the form, the num value in the Controller method parameter is null.

 

5. POJO (entity class) Type Binding

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 that the name property value in the input box must be consistent with the property of the above POJO object class to be mapped 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: All data is written to death and submitted directly. Values of the Integer, String, and Date types are supported.

Controller:

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

Make a breakpoint in the above Code and enter the URL to enter the Controller:

The above error is reported,The birthday attribute of User. java is of the Date type, but the input is of the string type, so it cannot be bound.

So the question is, how can we solve this problem when binding data of the Date type fails? This is the Date type converter we mentioned earlier.

  ① Define a converter from String type to Date type

Package com. ys. util; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; import org. springframework. core. convert. converter. converter; // The Converter interface needs to be implemented. Here, the String type is converted to the Date type public class DateConverter implements Converter <String, Date >{@ Overridepublic Date convert (String source) {// convert the string to the date type (Format: 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 () ;}// if the parameter binding fails, nullreturn null is returned ;}}

  ② Configure 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 "> <! -- Custom converter class name --> <bean class = "com. ys. util. DateConverter"> </bean> </property> </bean>

Enter the URL to view the Controller parameters again:

  

 

 

6. Bind the composite POJO (entity class) Type

Here we add an object 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();    }}

Add a private ContactInfo contactInfo attribute in User. java.

  

JSP page: Pay attention to the name of the property name, compound property name of User. java. Field name

      

Controller

  

The User object has the ContactInfo attribute. However, in the form code, you must use "attribute name (Object Type attribute). attribute name" to name the input name.

 

 

 

 

7. array binding

Requirement: We can query the information of all users and display them on the JSP page. Click Submit, you need to obtain the array set of all values of the User class id on the Controller page.

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

  

Controller. java

  

 

 

8. List binding

Requirement: Modify User information in batches

Step 1: Create UserVo. java and encapsulate the List <User> attribute

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;}}

Step 2: to simplify the process, we query all the User information directly from the Controller, and then 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 3: Modify the page value and click Submit

  

The name attribute defined in the input box on the JSP page is userList [$ {status. index}]. id. Here, we can directly use UserVo to obtain the User information submitted in batch on the page.

 

8. Map-Type Binding

First, add a Map <String, User> userMap attribute in UserVo.

Step 2: On the JSP page, check the attribute value of the <input> input box name.

  

 

Step 3: Get Page attributes in Controller

 

 

9. Problems Encountered

① Form cannot submit the content whose attribute is set to disabled in the input box

For example:

<Input type = "text" disabled = "disabled" name = "metadataName" maxlength = "50" placeholder = "Enter the English name of the model" title = "English name of the model ""/>

Has the disabled = "disabled" attribute. After being submitted to the Controller, the metadataName value is null.

Solution: change to readonly = "readonly"

Readonly: it is valid for input (text/password) and textarea. If it is set to true, you can get the focus, but cannot edit it. When submitting a form, the input item is submitted as the form content.

Disabled: For all form elements (select, button, input, textarea, etc.), if the value of disabled is set to true, the form input item cannot obtain the focus, all operations of the user are meaningless. When submitting a form, the input items of the form are not submitted.

 

Related Article

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.