欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring MVC 参数绑定

程序员文章站 2022-07-14 12:13:43
...

Spring MVC 参数绑定

客户端请求的参数到控制器功能处理方法上的参数的绑定,对于参数绑定非常灵活。

基本数据类型

package com.xxxx.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 参数绑定
 */
@Controller
public class ParamsController {
    /**
     * 基本类型数据绑定
     * 参数值必须存在。如果没有指定参数值,也没有设置参数默认值,则会报500异常。
     * @param age
     * @param money
     */
    @RequestMapping("data01")
    public void data01(int age,double money){
        System.out.println(age);
        System.out.println(money);
    }


    /**
     * 基本类型数据绑定
     * 通过注解 @RequestParam 标记一个形参为请求参数。(注解声明在形参的前面)
     * 可以通过注解的属性设置相关内容
     *      设置参数的默认值 defaultValue
     * @param age
     * @param money
     */
    @RequestMapping("data02")
    public void data02(@RequestParam(defaultValue = "18") int age,
                       @RequestParam(defaultValue = "10.0") double money){
        System.out.println(age);
        System.out.println(money);
    }

    /**
     * 基本类型数据绑定
     * 通过注解 @RequestParam 标记一个形参为请求参数。(注解声明在形参的前面)
     * 可以通过注解的属性设置相关内容
     *      设置参数的参数名(别名) name
     * @param age
     * @param money
     */
    @RequestMapping("data03")
    public void data03(@RequestParam(defaultValue = "18",name = "userAge") int age,
                       @RequestParam(defaultValue = "10.0",name = "userMoney") double money){
        System.out.println(age);
        System.out.println(money);
    }

}

包装类型

    /**
     * 包装类型数据绑定 (如果数据是基本类型,建议使用包装类型)
     *      客户端请求参数名与方法形参名保持一致,默认参数值为null
     *      可以通过 @RequestParam 的name属性设置参数的别名,defaultValue属性设置参数默认值
     * @param age
     * @param money
     */
    @RequestMapping("data04")
    public void data05(Integer age,Double money){
        System.out.println(age);
        System.out.println(money);
    }

字符串类型

    /**
     * 字符串类型数据绑定
     *      客户端请求参数名与方法形参名保持一致,默认参数值为null
     *      可以通过 @RequestParam 的name属性设置参数的别名,defaultValue属性设置参数默认值
     * @param userName
     * @param userPwd
     */
    @RequestMapping("data05")
    public void data05(String userName,String userPwd){
        System.out.println(userName);
        System.out.println(userPwd);
    }

数组类型

    /**
     * 数组类型数据绑定
     * 客户端传参形式:ids=1&ids=2&ids=3
     * @param ids
     */
    @RequestMapping("data06")
    public void data06(String[] ids) {
        for (String id : ids) {
            System.out.println(id + "---");
        }
    }

JavaBean 类型

User对象

package com.xxxx.springmvc.vo;

public class User {
    private Integer userId;
    private String userName;
    private String userPwd;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                '}';
    }
}

package com.xxxx.springmvc.controller;

import com.xxxx.springmvc.vo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 参数绑定
 */
@Controller
public class ParamsController {

    /**
     * JavaBean 数据绑定
     *      客户端请求的参数名与JavaBean对象的属性字段名保持一致
     * @param user
     */
    @RequestMapping("data07")
    public void data07(User user){
        System.out.println(user.toString());
    }

}

List 类型

此时 User 实体需要定义对应 list 属性。(对于集合的参数绑定,一般需要使用 JavaBean 对象进行包装)

phone实体

package com.xxxx.springmvc.vo;

public class Phone {

    private String num;

    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "Phone{" +
                "num='" + num + '\'' +
                '}';
    }
}

User对象

package com.xxxx.springmvc.vo;

import java.util.ArrayList;
import java.util.List;

public class User {
    private Integer userId;
    private String userName;
    private String userPwd;

    private List<Phone> phones = new ArrayList<Phone>();

    public List<Phone> getPhones() {
        return phones;
    }

    public void setPhones(List<Phone> phones) {
        this.phones = phones;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                ", phones=" + phones +
                '}';
    }
}

index.jsp页面定义

<%@page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<h2>Hello World!</h2>
<form action="data08" method="get">
    <input name="phones[0].num" value="123"/>
    <input name="phones[1].num" value="456"/>
    <button type="submit">提交</button>
</form>
</body>
</html>

Controller 方法

    /**
     * 集合数据绑定
     *      一般情况,集合会通过JavaBean对象进行封装。传参是通过JavaBean中属性字段名设置集合的指定下标值即可。
     * @param user
     */
    @RequestMapping("data08")
    public void data08(User user){
        System.out.println(user.toString());
    }

Set类型

Set 和 List 类似,也需要绑定在对象上,而不能直接写在 Controller 方法的参数中。但是,绑定Set数据时,必须先在Set对象中add相应的数量的模型对象。

package com.xxxx.springmvc.vo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class User {
    private int id;
    private String userName;
    private String userPwd;
    private Set<Phone> phones = new HashSet<Phone>();

    public User() {
        phones.add(new Phone());
        phones.add(new Phone());
        phones.add(new Phone());
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public Set<Phone> getPhones() {
        return phones;
    }

    public void setPhones(Set<Phone> phones) {
        this.phones = phones;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                ", phones=" + phones +
                '}';
    }
}

controller方法

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

表单页面

<%@page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<h2>Hello World!</h2>
<form action="data09" method="get">
    <input name="phones[0].num" value="123"/>
    <input name="phones[1].num" value="456"/>
    <input name="phones[2].num" value="789"/>
    <button type="submit">提交</button>
</form>
</body>
</html>

Map类型

package com.xxxx.springmvc.vo;

import java.util.*;

public class User {
    private int id;
    private String userName;
    private String userPwd;

    private Map<String,Phone> map = new HashMap<String,Phone>();

    public Map<String, Phone> getMap() {
        return map;
    }

    public void setMap(Map<String, Phone> map) {
        this.map = map;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }


    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                ", map=" + map +
                '}';
    }
}

Controller方法

    @RequestMapping("data10")
    public void data10(User user) {
        Set<Map.Entry<String, Phone>> set = user.getMap().entrySet();
        for (Map.Entry<String, Phone> entry : set) {
            System.out.println(entry.getKey() + "--" + entry.getValue().getNum());
        }
    }

表单页面

<%@page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<h2>Hello World!</h2>
<form action="data09" method="get">
    <input name="map[0].num" value="123"/>
    <input name="map[1].num" value="456"/>
    <input name="map[2].num" value="789"/>
    <button type="submit">提交</button>
</form>
</body>
</html>