Posting JSON to Spring MVC Controller
Spring MVC can be setup to automatically bind incoming JSON string into a Java object. Firstly, ensure you have jackson-mapper-asl included on the classpath:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Assuming the JSON string we want to bind represent a person object like this:
{
  name: "Gerry",
  age: 20,
  city: "Sydney"
}
Which will be bound into following Java class:
public class Person {
  private String name;
  private int age;
  private String city;
  // getters & setters ...
}
Declare the Spring MVC controller handler method like below. The handler method is mapped into path “addPerson” with method POST.
@RequestMapping(value = "/addPerson",
method = RequestMethod.POST,
headers = {"Content-type=application/json"})
@ResponseBody
public JsonResponse addPerson(@RequestBody Person person) {
logger.debug(person.toString());
return new JsonResponse("OK","");
}
Also pay attention to @ResponseBody and the returned JsonResponse object. Here JsonResponse is a class to return the result of the addPerson operation.
public class JsonResponse {
  private String status = "";
  private String errorMessage = "";
  public JsonResponse(String status, String errorMessage) {
    this.status = status;
    this.errorMessage = errorMessage;
  }
}
When converted to JSON this will look like this:
{
  status : "OK",
  errorMessage : ""
}
Below is an example jQuery based javascript handler that posts into the above Spring MVC handler and observe the returned value:
$.ajax({
  type: "POST",
  url: "addPerson",
  data: JSON.stringify({ name: "Gerry", age: 20, city: "Sydney" }),
  contentType: 'application/json',
  success: function(data) {
    if(data.status == 'OK') alert('Person has been added');
    else alert('Failed adding person: ' + data.status + ', ' + data.errorMessage);
  }
});
Posting JSON to Spring MVC Controller的更多相关文章
- Spring MVC Controller与jquery ajax请求处理json
		在用 spring mvc 写应用的时候发现jquery传递的[json数组对象]参数后台接收不到,多订单的处理,ajax请求: "}]}]} $.ajax({ url : url, typ ... 
- 前台JSON字符串,spring mvc controller也接收字符串
		前台JSON字符串,spring mvc controller也接收字符串 前台: $.post(url, { data : JSON.stringify(obj) }, function(data) ... 
- Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)
		Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ... 
- 转:【Spring MVC Controller单例陷阱】
		http://lavasoft.blog.51cto.com/62575/1394669/ Spring MVC Controller默认是单例的: 单例的原因有二:1.为了性能.2.不需要多例. 1 ... 
- Spring MVC Controller单例陷阱
		原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://lavasoft.blog.51cto.com/62575/1394669 Spr ... 
- Spring MVC Controller中GET方式传过来的中文参数会乱码的问题
		Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ... 
- Spring MVC Controller 单元测试
		简介 Controller层的单元测试可以使得应用的可靠性得到提升,虽然这使得开发的时间有所增加,有得必失,这里我认为得到的比失去的多很多. Sping MVC3.2版本之后的单元测试方法有所变化,随 ... 
- spring mvc controller中获取request head内容
		spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ... 
- 关于Spring MVC Controller 层的单元测试
		关于Spring MVC Controller 层的单元测试 测试准备工作: 1.搭建测试Web环境 2.注入Controller 类 3.编写测试数据 测试数据的文件名一定要与测试类的文件名相同,比 ... 
随机推荐
- leetcode:Single Number【Python版】
			1.用双重循环逐个遍历(超时) 2.用list B的append和remove函数(超时) 3.用dict B(AC) class Solution: # @param A, a list of in ... 
- ORA-10997:another startup/shutdown operation of this instance in progress解决方法
			SQL> startup ORA-10997: another startup/shutdown operation of this instance inprogress ORA-09967: ... 
- svn 报错及解决
			报错: svn: E155015: One or more conflicts were produced while merging r68508:73308 into '[分支]' -- reso ... 
- CC2530中串口波特率改为9600时单个数据包来不及接收的解决方案
			在调试CC2530过程中发现波特率改为9600时,单个包仅有3个Byte时,接收DMA就会启动 因而数据包被强迫拆分成多个,显然只要将接收DMA启动延时做到足够大即可. 具体修改内容如下图所示: 经过 ... 
- PHP接口开发加密技术实例原理与例子
			下面例子简单讲解PHP接口开发加密技术:如app要请求用户列表,api是“index.php?module=user&action=list”app生成token = md5sum (‘use ... 
- Eclipse/MyEclipse连接Hadoop集群出现:Unable to ... ... org.apache.hadoop.security.AccessControlExceptiom:Permission denied问题
			问题详细如下: 解决办法: <property> <name>dfs.premissions</name> <value>false</value ... 
- 操作系统-容器-Docker:如何将应用打包成为 Docker 镜像?
			ylbtech-操作系统-容器-Docker:如何将应用打包成为 Docker 镜像? 1.返回顶部 1. 虽然 DockerHub 提供了大量的镜像,但是由于企业环境的多样性,并不是每个应用都能在 ... 
- 学习笔记之FluentAssertions
			dotnet/src/MoqSample at master · haotang923/dotnet · GitHub https://github.com/htanghtang/dotnet/tre ... 
- 关于pandas里面的合并
			from pandas import * from numpy import * import json from pylab import * left = DataFrame({'key1':[' ... 
- [转]将字体嵌入程序资源中 C# Winform
			http://social.msdn.microsoft.com/Forums/officeapps/zh-CN/61b717ae-f925-443a-baad-2b85f2564826/cwinfo ... 
