Summary of SpringMVC Parameter Binding Learning [Front and Back End Data Parameter Transfer]

Keywords: Java JSP xml Database

Catalog

As a Controller layer (action in equivalent servlet s and struts), SpringMVC specially handles some requests for pages and then returns the data to the user through the view. Therefore, the importance of front-end and back-end data parameter transfer over springmvc is obvious. This article will summarize how parameters in springmvc receive front-end pages, that is, parameter binding in springmvc.
@

1. Binding mechanism

Form submission data is in k=v format. SpringMVC's parameter binding process binds form submission request parameters as parameters of the method in the controller, but it is important to note that the name of the submission form and the parameter name of the controller method are the same

2. Supported data types

In springmvc, there are default types of bindings that are supported, so the strong~framework of the springmvc framework is strong~.That is, you can use the following objects by defining the default supported type objects directly on the controller method parameters.

HttpServletRequest object
HttpServletResponse object
HttpSession object
Model/ModelMap Object

Supported data types are basic data types, wrapper classes, string types, entity types (JavaBean), collection data types (List, map collections, and so on), so the following is a specific analysis.

2.1, Basic Data Type, String

Actually, the following test classes already include basic data type, wrapper class, string type!
controller test code

@Controller
@RequestMapping("/param")
public class ParamController {
    @RequestMapping("/testBaseParam")
    public String testParam(String username,int password,Integer san){
        System.out.println("testParam Executed...");
        System.out.println("User name:"+username);
        System.out.println("Password:"+password);
        System.out.println("Password:"+san);
        return "success";
    }

index.jsp test code

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>Test Base Type</h3>
    <a href="param/testBaseParam?username=Liu Bei Tyre&password=123&san=456">Request Parameter Binding</a>
</body>
</html>

Running effect

Again, note that the name of the submission form and the name of the parameter must be the same, otherwise the binding fails

Summary of basic data types, wrapper classes, string types: 1. name of submission form and parameter names must be the same.2. Strict case sensitivity

2.2, Entity Type (JavaBean)

Case 1: Normal entity classes

dao test code

//Implement serializable interfaces
public class Account implements Serializable{
//Account database field
    private String username;
    private String password;
    private Double money;


...Omit getset Methods and toString Method

controller test code

//Request parameter binding encapsulates data into JavaBean classes
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("saveAccount Executed...");
        System.out.println(account);
        return "success";
    }

This is forwarded to param.jsp using index.jsp, with the following code:

<jsp:forward page="param.jsp"></jsp:forward>

The param.jsp test code is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    //Encapsulate data in Account class
    <form action="param/saveAccount" method="post">
        //Name: <input type="text" name="username"/><br/>
        //Password: <input type="text" name="password"/><br/>
        //Amount: <input type="text" name="money"/><br/>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

Test results

First case summary: Note that the name of the submission form and the name of the parameter must be the same, otherwise the binding fails ~Emphasize n times~

Second case: Entity class contains object properties

dao test code, note that the Account entity class contains the User object property

//Implement serializable interfaces
public class Account implements Serializable{
//Account database field
    private String username;
    private String password;
    private Double money;
//User Object Properties
    private User user;
    
...Omit getset Methods and toString Method

User Entity Class Code

//Implement serializable interfaces
public class User implements Serializable{
    private String uname;
    private Integer age;
    private Date date;

...Omit getset Methods and toString Method

The controller test code did not change, so it was not pasted out.
The param.jsp test code is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    //Encapsulate data in Account class
    <form action="param/saveAccount" method="post">
        //Name: <input type="text" name="username"/><br/>
        //Password: <input type="text" name="password"/><br/>
        //Amount: <input type="text" name="money"/><br/>
        //User name: <input type="text" name="user.uname"/><br/>
        //User age: <input type="text" name="user.age"/><br/>
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

Test results

Careful classmates may find that the date property is null because I did not pass a value to date in jsp.
Summary of the second scenario: Entity classes contain object attributes In this case, front-end and back-end parameters jsp format: Entity objects. Corresponding entity class attribute fields

2.3, Collection data type (List, map collection, etc.)

dao test class code:

 //Implement serializable interfaces 
public class Account implements Serializable{
//Account database field
    private String username;
    private String password;
    private Double money;
//Collection Object Properties
    private List<User> list;
    private Map<String,User> map;
  
...Omit getset Methods and toString Method

controller test code

//Request parameter binding encapsulates data into a class with a JavaBean collection type
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("saveAccount Executed...");
        System.out.println(account);
        return "success";
    }

The param.jsp test code is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
     //Encapsulate the data in the Account class, where there is a collection of list s and map s
    <form action="param/saveAccount" method="post">
        //Name: <input type="text" name="username"/><br/>
        //Password: <input type="text" name="password"/><br/>
        //Amount: <input type="text" name="money"/><br/>

        //User name: <input type="text" name="list[0].uname"/><br/>
        //User age: <input type="text" name="list[0].age"/><br/>

        //User name: <input type="text" name="map['one'].uname" /><br/>
        //User age: <input type="text" name="map['one'].age" /><br/>
        <input type="submit" value="Submit" />
    </form>

</body>
</html>

Test results

Summary: Collection type jsp format: list[0]. Properties

3. Parameter Request Chinese Scrambling Resolution

After the above test, it is normal that some students may have Chinese scrambling problems, because we have not set similar request.setCharacterEncoding("UTF-8") operation, in order to prevent Chinese scrambling, we can set up a global encoding filter uniformly.
Configuring the filter classes provided by Spring in web.xml

<!--Configure filters for resolving Chinese scrambling-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

4. Custom Type Converter

Since springmvc is so powerful that it provides default support for many types, there are still drawbacks. For example, when we save data of date type, springmvc only supports the format 2019/9/18. If you change to 2019-8-18, you will get an error. I can't just say no duck, so I'll just step on the pit again and let you look. The server cannot or will not be proce will be reported hereSs the request due to something that is perceived to be a client error exception, but that's okay, and I've written an article specifically addressing it. Click to enter , quit, start testing
jsp key code

 User Birthday: <input type="date" name="user.date" /><br/>

Error effect:

In order to provide strong evidence that the springmvc I just mentioned only supports the format of 9/18/2019, if it changes to 2019-8-18, an error will occur, then I've changed the jsp key code a bit, and changed type=date to type=text, as follows

    User Birthday: <input type="text" name="user.date" /><br/>

The effect is as follows

We want to think that any data type submitted by the form is all string type, but the Integer type is defined in the background, and the data can also be encapsulated, indicating that data type conversion is done by default within the Spring framework.What if you want to customize data type conversion?

4.1 Create a common class to implement the Converter interface

1. Create a common class to implement the Converter interface, and add the corresponding format conversion method, code as follows

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Convert string to date
 */
public class StringToDateConverter implements Converter<String,Date>{

    /**
     * String Incoming string
     */
    public Date convert(String source) {
        // judge
        if(source == null){
            throw new RuntimeException("Please pass in your data");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // Convert string to date
            return df.parse(source);
        } catch (Exception e) {
            throw new RuntimeException("Be finished~Error in data type conversion");
        }
    }

}

Configuring custom type converters in 4.2 Springmvc.xml

  1. Register a custom type converter and write the configuration in the springmvc.xml configuration file
<!--Configure Custom Type Converter-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.gx.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>


    <!-- open SpringMVC Support for framework notes -->
    <mvc:annotation-driven conversion-service="conversionService"/>

The results are as follows:

Summary of Custom Type Converter steps:
1. Create a common class to implement Converter interface and add corresponding format conversion methods
2. Register a custom type converter and write the configuration in the springmvc.xml configuration file

Don't forget to register in Annotation Driver after configuring, that is, this sentence

 <mvc:annotation-driven conversion-service="conversionService"/>

5. Summary of Final Parameter Binding Learning

If this article helps you a little, please give a compliment, thank you~

Finally, if there are any deficiencies or inaccuracies, you are welcome to correct the criticism and appreciate it!If in doubt, please leave a message and reply immediately!

Welcome to pay attention to my public number, discuss technology together, yearn for technology, and pursue technology. Well, you're friends now.

Posted by Thethug on Sun, 08 Dec 2019 23:31:39 -0800