zoukankan      html  css  js  c++  java
  • springmvc中 @RequestBody 接收参数问题

    从前台用js向 springmvc中传递 json。在controller中转换为java对象需要用 @RequestBody 注解。但是传递时有几个问题可能会导致无法访问。

    1.ajax中必须用json对象:JSON.stringify({"name":name,"age":age,"sex":sex})

    2.ajax中必须设置 contentType:"application/json",

    3.否则会报 415或者400错误。

    直接上代码:

    前台:

    
    <html>
      <head>
        <title></title>
      </head>
      <body>
      <div>
        name:<input type="text" id="name"> <br>
        sex:<input type="text" id="sex"><br>
        age:<input type="text" id="age"><br>
        <button type="button" id="btn">提交</button>
      </div>
      <script src="js/jquery-3.3.1.js"></script>
      <script>
    
        $("#btn").click(function(){
            var name = $("#name").val();
            var sex = $("#sex").val();
            var age = $("#age").val();
            $.ajax({
                type: "POST",
                url: "test03",
                contentType:"application/json",
                data: JSON.stringify({"name":name,"age":age,"sex":sex}),
                success: function(data){
                    if(data.msg==1){
                        alert("success");
                    }else{
                        alert("error");
                    }
                }
            });
        })
      </script>
      </body>
    </html>
    
    

    controller

       @ResponseBody
        @RequestMapping("/test03")
        public Map<String,Object> test03(@RequestBody User user){
    
            Map<String,Object> map = new HashMap<>();
            if(user!=null){
                map.put("msg","1");
            }else{
                map.put("msg","0");
            }
    
            return map;
        }
    

    实体类

    public class User {
    
        private String name;
        private int age;
        private String sex;
    
        public User() {
        }
    
        public User(String name, int age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    }
    
    
    
  • 相关阅读:
    <hdu2072>单词数(set容器,string类应用)
    志愿者选拔
    Game of Life
    <LightOJ 1338> Hidden Secret!
    Miss Kitty and Her Little Ice Cream Shop(水题)
    约瑟夫问题
    <FZU 1019>猫捉老鼠
    <cf>System of Equations(水题)
    Palindromic Numbers (III)(回文数,较麻烦)
    <cf>Solitaire(DFS or DP)
  • 原文地址:https://www.cnblogs.com/jixu8/p/11246183.html
Copyright © 2011-2022 走看看