SpringMVC, as a Controller layer (equivalent servlets and Actions in Struts), is designed to handle requests for pages and then return data to the user through the view. Therefore, we can see the importance of front-end data parameter passing relative to SpringMVC. This article will summarize how springMVC receives the parameters of the foreground page, namely the parameter binding issue in SpringMVC. @[toc]

1. Binding mechanism

The form submission data is in k= V format. SpringMVC’s parameter binding process binds the request parameters of the form submission as parameters of the controller method, but note that the name of the submitted form is the same as the parameter name of the Controller method

2. Supported data types

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

HttpServletRequest object HttpServletResponse object HttpSession object Model/ModelMap object

The supported data types include basic data types, wrapper classes, string types, entity types (Javabeans), and collection data types (lists, maps, etc.).

2.1. Basic data types and strings

In fact, the following test classes I have included the 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("Username:"+username);
        System.out.println("Password:"+password);
        System.out.println("Password:"+san);
        return "success";
    }
Copy the code

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? </a> </body> </ HTML >Copy the code

Running effect

Again, note that the name of the submitted form and the name of the parameter must be the same or the binding will fail

2.2 Entity Types (JavaBean)

Case one: normal entity classes

Dao test code

// Implement serializable interface
public class Account implements Serializable{
//Account database field
    private String username;
    private String password;
    privateDouble money; . Omit getSet and toString methodsCopy the code

Controller test code

// Request parameter bindings encapsulate data into JavaBean classes
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("SaveAccount executes...");
        System.out.println(account);
        return "success";
    }
Copy the code

This is forwarded to param.jsp with index.jsp as follows:

<jsp:forward page="param.jsp"></jsp:forward>
Copy the code

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 <form Action ="param/saveAccount" method="post"> name: <input type="text" name="username" <input type="text" name="password" /> < input type = "text" name = "money" / > < br / > < input type = "submit" value = "submit" / > < / form > < / body > < / HTML >Copy the code

The test results

The second case: the entity class contains object attributes

The DAO tests the code, noting that the Account entity class contains User object attributes

// Implement serializable interface
public class Account implements Serializable{
//Account database field
    private String username;
    private String password;
    private Double money;
//User object properties
    privateUser user; . Omit getSet and toString methodsCopy the code

User entity class code

// Implement serializable interface
public class User implements Serializable{
    private String uname;
    private Integer age;
    privateDate date; . Omit getSet and toString methodsCopy the code

The Controller test code hasn’t changed, so I won’t post it. 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 <form Action ="param/saveAccount" method="post"> name: <input type="text" name="username" <input type="text" name="password" /><br/> <input type="text" name="user.uname" /><br/> < input type = "text" name = "user. Age" / > < br / > < input type = "submit" value = "submit" / > < / form > < / body > < / HTML >Copy the code

The test results

Entity object. Corresponding entity class attribute field

2.3 Collection data types (List, Map collection, etc.)

Dao test class code:

 // Implement serializable interface
public class Account implements Serializable{
//Account database field
    private String username;
    private String password;
    private Double money;
// Collection object properties
    private List<User> list;
    privateMap<String,User> map; . Omit getSet and toString methodsCopy the code

Controller test code

// Request parameter bindings encapsulate data into JavaBean classes with collection types
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("SaveAccount executes...");
        System.out.println(account);
        return "success";
    }
Copy the code

The param.jsp test code is as follows:

<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> </title> </head> <body> <form action="param/saveAccount" method="post"> Name: <input type="text" name="username" /> <input type="text" name="password" /><br/> <input type="text" name="list[0].uname" /><br/> user age: < input type = "text" name = "map [' one '] uname" / > < br / > user age: < input type = "text" name = "map [r]. 'one' age" / > < br / > < input type = "submit" value = "submit" / > < / form > < / body > < / HTML >Copy the code

The test results

3. The parameter request Chinese characters are garbled

After the test, some students may appear garbled question in Chinese, this is very normal, because we don’t have set up similar request. SetCharacterEncoding (” utf-8 “) operation, in order to prevent the Chinese garbled solution, we can set the global unified coding filter. Configure the spring-provided filter classes in web.xml

<! <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>Copy the code

4. Custom type converters

Since SpringMVC is powerful enough to provide default support for many types, there are still some defects. For example, when we save date data, SpringMVC only supports 2019/9/18. If we change it to 2019-8-18, we will get an error. So I’m just going to step in one more pit and let you look, The server cannot or will not process The request due to something that is perceived to be a client error. I also wrote an article specifically to reject this exception, clicked in, left it alone, and started testing JSP key code

User birthday: <input type="date" name="user.date" /><br/>
Copy the code

Error effect:

2019/9/18
The 2019-8-18

User birthday: <input type="text" name="user.date" /><br/>
Copy the code

Results the following

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

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 String passed in */
    public Date convert(String source) {
        / / determine
        if(source == null) {throw new RuntimeException("Please pass in the data.");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // Convert the string to a date
            return df.parse(source);
        } catch (Exception e) {
            throw new RuntimeException("Screwed up ~ data type conversion error"); }}}Copy the code

4.2 Configuring a custom type converter in SpringMVC.xml

  1. Register a custom type converter and write the configuration in the springMVC.xml configuration file
<! - configure the 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> <! < MVC :annotation-driven Conversion -service="conversionService"/>Copy the code

The effect is as follows:

Don’t forget to register in the annotation driver after configuration, i.e

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

5. Finally, summary of parameter binding learning

If this article helped you at all, please give it a thumbs up. Thanks

Finally, if there is insufficient or improper place, welcome to criticize, grateful! If you have any questions welcome to leave a message, absolutely the first time reply!

Welcome everyone to pay attention to my public number, discuss technology together, yearning for technology, the pursuit of technology, good come is a friend oh…