【转】 SpringMVC中controller接收Json数据

本文详细解析了前端与后端数据交互的过程,重点介绍了使用JSON格式进行数据传输的方法,包括如何设置正确的contentType和dataType,以及在SpringMVC框架中如何使用@RequestBody和@ResponseBody注解来处理JSON数据。

转自:https://blog.csdn.net/a545415/article/details/77964823

dataType和contentType区分:

contentType: 发送信息至服务器时内容编码类型,简单说告诉服务器请求类型的数据

   在调试js时候通过chrome的F12或firefox的firebug查看请求参数时,尤其请注意head

   默认值: "application/x-www-form-urlencoded"

dataType:告诉服务器,我要想什么类型的数据,除了常见的json、XML,还可以指定 html、jsonp、script或者text

SpringMVC中controller接收Json数据

1.jsp页面发送ajax的post请求:

function postJson(){
    var json = {"username" : "imp", "password" : "123456"};
    $.ajax({
        type : "post",
        url : "<%=basePath %>ajaxRequest",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data: JSON.stringify(json),
        success : function(data){
            alert("username:"+data.username+"   id:"+data.id);
        },
        error : function(){
            alert("请求失败");
        }
    })
}

注意:

1.在发送数据时,data键的值一定要写成JSON.stringify(json),将数据转换成json字符串格式,否则会抛出异常

2.basePath是项目根目录:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

2.controller接收请求:

    @ResponseBody
    @RequestMapping(value="/ajaxRequest",method=RequestMethod.POST)
    public User ajaxRequest(@RequestBody User user){
        System.out.println(user);
        return user;
    }

注意:

1.@ResponseBody修饰的方法返回的数据,springmvc将其自动转换成json格式,然后返回给前端

2.@RequestBody修饰目标方法的入参,可以将ajax发送的json字符串(或者JSOn对象的字符串形式)赋值给入参。当然这里的入参user是我们自定义的实体类型。

3.最后将user返回,springmvc自动将其转换成json返回给前端

4、其实 @RequestBody接收的是一个Json对象的字符串,而不是一个Json对象。然而在ajax请求往往传的都是Json对象,后来发现用 JSON.stringify(data)的方式就能将对象变成字符串。同时ajax请求的时候也要指定dataType: "json",contentType:"application/json" 这样就可以轻易的将一个对象或者List传到Java端,使用@RequestBody即可绑定对象或者List.

其它参考

https://blog.csdn.net/Edison_03/article/details/79826656

 前端js发送ajax请求( application/x-www-form-urlencoded )

 var jsonObj = {"openid":"xxx","username":"Ed sheeran","password":"123"};
          /*
              Jquery默认Content-Type为application/x-www-form-urlencoded类型
           */
          $.ajax({
              type: 'POST',
              url: "/login",
              dataType: "json",
              data: JSON.stringify(jsonObj),
              success: function(data) {
                  console.log(data)
              },
              error: function() {
                  console.log("fucking error")
              }
          });

      后端Servlet接受参数。前端报 200,后端报 返回值都是null

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(HttpServletRequest request){
      System.err.println(request.getParameter("openid"));
      System.err.println(request.getParameter("username"));
      System.err.println(request.getParameter("password"));
}



后端改 @RequestParam 接受参数。前端报 404,后端报 Required String parameter ‘username’ is not present

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestParam("username") String username,
                    @RequestParam("password") String password,
                    @RequestParam("openid") String openid){
      System.err.println(username);
      System.err.println(password);
      System.err.println(openid);
  }


后端改 @RequestBody 接受参数。

前端报 415,后端报 Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported

Http status 415 Unsupported Media Type

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Map<String,Object> map){
      System.err.println(map.get("username"));
      System.err.println(map.get("password"));
      System.err.println(map.get("openid"));
  }


前端加 contentType : “application/json”。前端报 200,后端 能接受到参数

   

$.ajax({
              type: 'POST',
              url: "/login",
              dataType: "json",
              data: JSON.stringify(jsonObj),
              contentType : "application/json",
              success: function(data) {
                  console.log(data)
              },
              error: function() {
                  console.log("fucking error")
              }
          });

 

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Map<String,Object> map){
      System.err.println(map.get("username"));
      System.err.println(map.get("password"));
      System.err.println(map.get("openid"));
}
}



有时候,我想在后端使用对象来获取参数。前端报 200,后端 也ok

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Form form){
      System.err.println(form);
}

public class Form {
  private String openid;
  private String username;
  private String password;

  public String getOpenid() {
      return openid;
  }

  public void setOpenid(String openid) {
      this.openid = openid;
  }

  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;
  }

  @Override
  public String toString() {
      return "Form{" +
              "openid='" + openid + '\'' +
              ", username='" + username + '\'' +
              ", password='" + password + '\'' +
              '}';
  }
}

最终选择交互方式

前端 application/json,上传 josn字符串, 后端 使用对象 或者 Map

前端

       var jsonObj = {"openid":"xxx","username":"Ed sheeran","password":"123"};
          /*
              Jquery默认Content-Type为application/x-www-form-urlencoded类型
           */
          $.ajax({
              type: 'POST',
              url: "/login",
              dataType: "json",
              data: JSON.stringify(jsonObj),
              contentType : "application/json",
              success: function(data) {
                  console.log(data)
              },
              error: function() {
                  console.log("fucking error")
              }
          });

后端代码1

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Form form){
      System.err.println(form);
}
}

后端代码2

@Controller
public class LoginController {
  @PostMapping("/login")
  public void login(@RequestBody Map<String,Object> map){
      System.err.println(map.get("username"));
      System.err.println(map.get("password"));
      System.err.println(map.get("openid"));
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值