Spring MVC receives form data and data binding

There are three ways to receive form data.

 

1. Receive form data using simple types (bind simple data types)

Form:

  <form action="${pageContext.request.contextPath}/userController/handler" method="post">
    User name: < input name = "username" type = "text" / > < br / >
    Password: < input name = "password" type = "password" / > < br / >
    Age: < input name = "age" type = "number" / > < br / >
    < button type = "submit" > submit < / button >
  </form>

action will prompt, but we need to add ${pageContext.request.contextPath} in front to get the project name (/ the form of project name). Otherwise, we will splice the following path directly behind the domain name.

 

 

controller:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public ModelAndView handler(String username, String password, int age){
        ModelAndView mav = new ModelAndView("user_info");
        mav.addObject("username", username);
        mav.addObject("password", password);
        mav.addObject("age", age);
        return mav;
    }

}

The parameter name should be consistent with the name of the form field.

Spring MVC automatically converts the request parameters to the required data types.

 

If the form has many fields, the business method needs to write many parameters, which is too cumbersome to recommend.

 

 

 

 

2. Use pojo class to receive form data (bind pojo type)

pojo:

public class User {
    private String username;
    private String password;
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

The property name should be consistent with the name of the form field.

 

 

controller:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public ModelAndView handler(User user){
        ModelAndView mav = new ModelAndView("user_info");
        mav.addObject("user", user);
        return mav;
    }

}

 

Recommended.

 

 

 

 

3. Use extension class to receive form data (wrapper class bound to pojo)

Extension class:

public class UserExt {
    private User user;
    //Other member variables are omitted here

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Write the bean as a member variable.

 

 

Form:

  <form action="${pageContext.request.contextPath}/userController/handler" method="post">
    User name: < input name = "user. Username" type = "text" / > < br / >
    Password: < input name = "user. Password" type = "password" / > < br / >
    Age: < input name = "user. Age" type = "number" / > < br / >
    < button type = "submit" > submit < / button >
  </form>

The user here corresponds to the member variable name in the extension class.

 

 

controller:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public ModelAndView handler(UserExt userExt){
        ModelAndView mav = new ModelAndView("user_info");
        mav.addObject("userExt", userExt);
        return mav;
    }

}

 

Use extension class to receive parameters, mainly because some data from the form does not belong to entity class, and other member variables are needed to receive.

 

 

 

 

Data receiving of radio box and check box

Radio boxes can be received as normal types.

 

Check boxes are often used to check multiple options at the same time, such as selecting hobbies, deleting in batch, etc. (the same name, multiple value s).

The check box is received by an array. The name of the check box should be the same as the array name.

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public ModelAndView handler(String[] hobby){
        ModelAndView mav = new ModelAndView("user_info");
        mav.addObject("hobby",hobby);
        return mav;
    }

}

 

 

 

 

Batch modify, use List to receive

Sometimes we need to insert and modify in batch.

For example, the view lists the information of multiple users in the form of a table. The administrator has modified the information of multiple users on the page. Now to submit the modification, you need to use list < user > to transfer the data. The same is true for batch adding.

You can't directly use list < user > to receive parameters. You need to use a wrapper class to wrap them.

 

Packaging category:

public class UserVO {
    private List<User> list;

    public List<User> getList() {
        return list;
    }

    public void setList(List<User> list) {
        this.list = list;
    }
}

VO has only one property and its getter and setter methods.

 

 

Form:

  <form action="${pageContext.request.contextPath}/userController/handler" method="post">
    User1: <br />
    username: <input name="list[0].username" type="text"><br />
    password: <input name="list[0].password" type="password"><br /><br />

    User2: <br />
    id: <input name="list[1].username" type="text"><br />
    name: <input name="list[1].password" type="password"><br /><br />

    <button type="submit">Submission</button>
  </form>

Here the list corresponds to the member variable name of the wrapper class.

 

 

controller:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public ModelAndView handler(UserVO userVO){
        ModelAndView mav = new ModelAndView("user_info");
        mav.addObject("list", userVO.getList());
        return mav;
    }

}

 

 

 

 

Receipt of date

Sometimes you need to receive the date the form is delivered, such as a birthday.

 

There are two receiving methods in the background:

  • Receive date using String

If you do not carry out the relevant calculation, use String to indicate the date; if you want to do the relevant calculation, first use String to receive the date, and convert the String to Date in the business method (which can be encapsulated as a tool class and invoked in the business method).

Use < input type="text" / > and < input type = "date" / > for forms, and strictly verify the date format.

 

  • Receive Date with Date

The forms can use < input type="text" / > and < input type = "date" / > respectively. If type="text" is used, the date format can only be year / month / day (/ separated).

 

 

 

 

DataBinder data binding

The concept of data binding: binding the content of request parameters with the parameters of business methods in the controller, such as the submission of form data.

 

 

Data binding process:

(1) Spring MVC passes the ServletRequest object to DataBinder

 

(2) Spring MVC obtains the parameter table (parameter name) from the signature (Declaration) of the controller's business method and passes it to DataBinder

 

(3) DataBinder calls ConversionService to convert and format the request parameters in ServletRequest

(ConversionService will call the corresponding Converter according to the original type - target type to perform data conversion. Spring MVC has built-in common type converters. We can also customize type converters.)

 

(4) DataBinder calls Validator to verify whether the transformed request parameter is legal

 

(5) DataBinder calls BindingResult, assigns the request parameters to the corresponding parameters in the business method, and completes the data binding.

 

 

 

 

Solve the Chinese disorder code of data transmitted from the front end

Use the encoding filter provided by spring mvc to filter all requests.

 

Configure 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 all requests-->
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

 

 

 

@RequestParam required request parameters

controller:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public String handler(int user_id,Model model){
        model.addAttribute("user_id", user_id);
        return "user_info";
    }

}

Even if there is no user ID field in the request parameter, this business method will be called to process, that is to say, the parameter is not required to be passed.

 

 

If the parameter is required, this field is required in the HTTP request parameter, as follows:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public String handler(@RequestParam("user_id") int user_id,Model model){
        model.addAttribute("user_id", user_id);
        return "user_info";
    }

}

Add @ RequestParam at the top of the parameter table, which contains the required request parameters.

If this parameter is not passed, the business method will not be called and an error will be reported directly.

 

 

Be careful:

Required and required are not concepts. Required means that this field must exist in the request parameter. Only this field is required. The value can be empty.

If a form field (with the name attribute) is submitted without filling in, there is this field in the request parameter, but the value is empty.

 

 

You can set whether or not it is required:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public String handler(@RequestParam(value = "user_id",required = false) int user_id,Model model){
        model.addAttribute("user_id", user_id);
        return "user_info";
    }

}

The default value is true -- required. The parameter is not passed and an error is reported directly.

false -- it is not necessary. If it is passed or not, the business method will be called.

 

 

You can set the default value:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler")
    public String handler(@RequestParam(value = "user_id",defaultValue = "0") int user_id,Model model){
        model.addAttribute("user_id", user_id);
        return "user_info";
    }

}

If this parameter is not passed, the default value is automatically used.

Tags: Java Spring encoding xml Attribute

Posted on Fri, 31 Jan 2020 03:15:05 -0800 by powlow