zoukankan      html  css  js  c++  java
  • 3、请求参数绑定

    (1)多个请求参数的绑定

    请求链接

     <a href="selectUser?username=xiao&age=18">点击</a>
    
    /**
     * 参数名相同时,spring会通过反射将请求参数的值赋值该方法的参数
     * 当参数名不一致时,通过@RequestParam注解解决
     */
    @RequestMapping(value = "/selectUser")
    @ResponseBody
    public String selectUser(@RequestParam("username") String name, Integer age){
        return name + age;
    }
    

    (2)请求参数绑定实体类型

    实体类

    public class User {
        //基本数据类型
        private String username;
        private Integer age;
         //省略get、set、toString方法
    

    发送请求

    <a href="selectUser?username=xiao&age=18">点击</a>
    

    请求映射

    @RequestMapping("/selectUser")
    @ResponseBody
    public String selectUser2(User user){
        return user.toString();
    }
    

    (3)实体类的属性是实体类型参数绑定

    User 类

    Account类

    public class Account {
    
        private String id;
        private Double money;
    
    
    public class User {
        //基本数据类型
        private String username;
        private Integer age;
        //实体类属性是实体类型
        private Account account;
    

    请求链接

    <a href="user/selectUser?username=xiao&age=18&account.id=120658">点击</a>
    

    请求映射

    /**请求参数绑定实体类
     * 要求实体类的属性与请求参数的参数名相同
     */
    @RequestMapping("/selectUser")
    @ResponseBody
    public String selectUser2(User user){
        return user.toString()+ user.getAccount().toString();
    }
    

    (4)参数绑定实体类集合属性

    实体类

    public class User {
        //基本数据类型
        private String username;
        private Integer age;
    
        private List<Account> accountList;
        private Map<String, Account> accountMap;
    

    表单

    <form action="user/selectUser" method="post">
        姓名:<input type="text" name="username"><br>
        年龄:<input type="text" name="age"><br>
        <h3>List</h3>
        账户:<input type="text" name="accountList[0].id"><br>
        金额:<input type="text" name="accountList[0].money"><br>
        <h3>Map</h3>
        账户:<input type="text" name="accountMap['ac'].id"><br>
        金额:<input type="text" name="accountMap['ac'].money"><br>
    
        <input type="submit" value="提交">
    </form>
    

    controller

    /**请求参数绑定实体类
     * 要求实体类的属性与请求参数的参数名相同
     */
    @RequestMapping("/selectUser")
    @ResponseBody
    public String selectUser2(User user){
        return user.toString() + user.getAccountList().toString() + user.getAccountMap().toString();
    }
    
  • 相关阅读:
    springboot 项目部署到服务器
    Thymeleaf的注意项
    springboot定时器
    springboot
    随笔
    mysql数据库连接超过8小时失效的解决方案(springboot)
    Druid连接池与spring配置
    IDEA快捷键
    jsonp解决跨域,用div,css,js,jq实现textarea自适应高度
    mysql的查询、子查询及连接查询(商城查询常用)
  • 原文地址:https://www.cnblogs.com/Ryuichi/p/13377268.html
Copyright © 2011-2022 走看看