报文信息转换器,将请求报文转换为java对象,或将Java对象转换为响应报文
可以获取请求体,需要在控制器方法设置一个形参,使用@RequestBody进行标识,
当前请求的请求体就会为当前注解所标识的形参赋值
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String requestBody){
System.out.println(requestBody);
return "success";
}
输出结果:username=admin&password=123
用于标识一个控制器方法,可以在该方法的返回值直接作为响应报文的响应体相应到浏览器
@RequestMapping(value = "/testResponseBody",produces = "application/json;charset=utf-8")
@ResponseBody
public String testResponseBody(){
return "今天星期二";
}
produces = "application/json;charset=utf-8"处理响应体中文乱码问题
封装请求报文的一种类型,需要在控制器方法的形参中设置该类型的形参,
当前请求的请求报文就会赋值给该形参,就可以通过getHeaders()获取请求头信息,
通过getBody()获取请求体信息
@RequestMapping("/testRequestEntity")
public String testRequestEntity(RequestEntity requestEntity){
System.out.println("requestHeader:" + requestEntity.getHeaders());
System.out.println("requestBody:" + requestEntity.getBody());
return "success";
}
输出结果
// requestHeader[host:"localhost:8080", connection:"keep-alive",
// content-length:"27", cache-control:"max-age=0",
// sec-ch-ua:""Chromium";v="112", "Microsoft Edge";v="112",
// "Not:A-Brand";v="99"", sec-ch-ua-mobile:"?0",
// sec-ch-ua-platform:""Windows"", upgrade-insecure-requests:"1",
// origin:"http://localhost:8080",
// user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.34",
// accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", sec-fetch-user:"?1", sec-fetch-dest:"document", referer:"http://localhost:8080/springMVC_06_Converter_war/", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", cookie:"Idea-adfcd06e=853c44ef-1c56-4446-aea2-437cb50adfbb", Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]
// requestBodyusername=admin&password=123
用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文
1.导入jackson的依赖
com.fasterxml.jackson.core
jackson-databind
2.14.1
2.在springMVC核心配置文件中开启mvc注解驱动,此时在HandlerAdaptor中
会自动装配一个消息转换器:MappingJackson2HttpMessageConverter,可以将
响应到浏览器的java对象转换为json格式的字符串
3.在处理器方法上使用@ResponseBody注解进行标识
4.将java对象直接作为控制器的返回值返回,就会自动的将其转换为json格式的字符串
@RequestMapping("/testResponseUser")
@ResponseBody
public User testResponseUser(){
return new User(1001,"admin","123456",23,"男");
}