作用:
该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格式的 数据如:json,xml 等,通过 Response 响应给客户端
使用示例
需求: 使用@ResponseBody 注解实现将 controller 方法返回对象转换为 json 响应给客户端。
前置知识点: Springmvc 默认用 MappingJacksonHttpMessageConverter 对 json 数据进行转换,需要加入 jackson 的包。
jsp 中的代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>string测试</title>
<script src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="btn">发送ajax的请求</button>
<script>
//页面加载
$(function () {
$("#btn").click(function () {
$.ajax({
//编写json格式,设置属性和值
url:"user/testAjax", //请求路径
contentType:"application/json;charset=UTF-8", //编码格式
data:'{"username":"hehe","password":"123","ega":"30"}', //传值
dataType:"json",
type:"post", //请求方式
success:function (data) {
//data服务器端响应的json的数据,进行解析
}
})
});
});
</script>
</body>
</html>
控制器中的代码:
package Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.User;
/**
* 我是
*/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
/**
* 模拟异步请求响应
*/
@RequestMapping("/testAjax")
public void testAjax(@RequestBody String body){
System.out.println("testAjax执行了....");
System.out.println(body);
}
}