第一步 导入相关Jar包
- 在pom.xml中导入json和jackson包,导入这些包才能使用注解方式来封装json数据
- XMl导入代码:
<!-- jackson包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<!-- json包-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
二.前端Jquery代码
<script type="text/javascript">
function useAjax() {
$.ajax({
url: "ajax.do",
type: 'post',
dataType: 'json',
data: {name:"你好"},
success:return_json
});
function return_json(json){
alert(json.name);
}
}
</script>
<button οnclick="useAjax()">ajax请求</button>
三.Controller 中处理代码
- 处理方式一,使用RequestParam接收值并传递
@RequestMapping(value = "/ajax.do", method = RequestMethod.POST)
@ResponseBody
public JSONObject useAjax(@RequestParam("name") String parameter){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", parameter);
return jsonObject;
}
- 方式二,使用HttpServletRequest接收数据。
@RequestMapping(value = "/ajax.do", method = RequestMethod.POST)
@ResponseBody
public JSONObject ajaxdemo(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
String parameter = req.getParameter("name");
jsonObject.put("name", parameter);
return jsonObject;
}