/** * * 总结:使用了 * – 使用 @RequestBody / @ResponseBody 对处理方法进行标注 – 使用 HttpEntity<T> / ResponseEntity<T> 作为处理方法的入参或返回值 其实spring会自动的把请求信息或者响应信息,转换为所对应的java数据或者客户端所期望的请求数据 * 处理 JSON 1. 加入 jar 包: • 2. 编写目标方法,使其返回 JSON 对应的对象或集合 • 3. 在方法上添加 @ResponseBody 注解 HttpMessageConverter<T> 是 Spring3.0 新添加的一个接口, 负责将请求信息转换为一个对象(类型为 T),@RequestBody,@RequestEntity 将对象(类型为 T)输出为响应信息,@ResponseBody 使用 HttpMessageConverter<T> 将请求信息转化并绑定到处理方法的入 参中或将响应结果转为对应类型的响应信息,Spring 提供了两种途径: – 使用 @RequestBody / @ResponseBody 对处理方法进行标注 – 使用 HttpEntity<T> / ResponseEntity<T> 作为处理方法的入参或返回值 • 当控制器处理方法使用到 @RequestBody/@ResponseBody 或 HttpEntity<T>/ResponseEntity<T> 时, Spring 首先根据请求头或响应头的 Accept 属性选择匹配的 HttpMessageConverter, 进而根据参数类型或 泛型类型的过滤得到匹配的 HttpMessageConverter, 若找不到可用的 HttpMessageConverter 将报错 * @param json * @param httpEntity * @return */
@RequestMapping("RequestBody")
@ResponseBody
public Map<String, Object> RequestBodyAndResponseBody(
@RequestBody String json,
HttpEntity<String> httpEntity
){
String body = httpEntity.getBody();
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", 1);
return retMap;
}
@RequestMapping("ResponseEntity")
public ResponseEntity ResponseEntity(
HttpEntity<String> httpEntity
){
String body = httpEntity.getBody();
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", 1);
ResponseEntity<Map<String,Object>> responseEntity = new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
return responseEntity;
}
还没有评论,来说两句吧...