SpringMVC+JSP中关于JQuery ajax提交的Content-Type参数设置application/json和application/x-www-form-urlencoded区别

页面是用的JSP,后台用的Spring MVC

使用JQuery的ajax需要设置Content-Type,Content-Type的设置有以下几种常用的

"Content-Type": "application/x-www-form-urlencoded"    //适用于大部分情况
"Content-Type": "application/json"    //适用于复杂JSON数据的提交
"Content-Type": "multipart/form-data"    //适用于文件上传

application/x-www-form-urlencoded

application/x-www-form-urlencoded是JQuery ajax默认的提交方式,当不写contentType时即是此种方式,代表使用表单形式提交。

JSP:

$.ajax({
  type: "POST",
  url: "${basePath}/comment",
  contentType: "application/x-www-form-urlencoded", 
  dataType: "json", //表示返回值类型,不必须
  data: {comment: 'appblog.cn'},
  success: function (result) {
    alert(result);
  }
});

后台:

@RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST)
@ResponseBody
public Result reviewOrder(@PathVariable("orderId") Long orderId, HttpServletRequest request) {
    String comment = request.getParameter("comment");

}

application/json

使用application/x-www-form-urlencoded只能提交简单类型的json数据,当json数据很复杂时就须要使用application/json

JSP:

$.ajax({
  type: "POST",
  url: "${basePath}/comment",
  contentType: "application/json", //必须有
  dataType: "json", //表示返回值类型,不必须
  data: JSON.stringify({'comment': 'appblog.cn'}),
  success: function (result) {
    alert(result);
  }
});

后台

@RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST)
@ResponseBody
public Result reviewOrder(@PathVariable("orderId") Long orderId, @RequestBody Review review, HttpServletRequest request) {
    String comment1 = request.getParameter("ids");    //输出null
    String comment2 = review.getComment();
}
public class Review {
    String comment;

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }
}

也可以使用JSONObject

@RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST)
@ResponseBody
public Result reviewOrder(@PathVariable("orderId") Long orderId, @RequestBody JSONObject object, HttpServletRequest request) {
    String comment = object.getString("comment");
}

总结:当使用application/x-www-form-urlencoded时其实JSP会默认把json数据认为是一个对象,而使用application/json时需要向后台传入一个JSON字符串,所以要用JSON.stringify函数把JSON对象转成json字符串。

上一篇 Java服务端开发记录
下一篇 整合Shiro出现org.quartz.Scheduler错误
目录
文章列表
1 Spring Cloud服务网关zuul初级篇
Spring Cloud服务网关zuul初级篇
2
Dart中的类与对象
Dart中的类与对象
3
Windows下安装RabbitMQ
Windows下安装RabbitMQ
4
AWS CloudWatch 警报添加恢复操作
AWS CloudWatch 警报添加恢复操作
5
CentOS 7与RHEL 7的systemd指令
CentOS 7与RHEL 7的systemd指令
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。