Spring mvc Json 的正确返回姿势
我们经常都需要封装统一JSON格式 例如以下形式
{“data”:“输出的数据”,“code”:“响应代码”,“msg”:“响应信息”}
/*** Created by linli on 2017/7/31.*/public class Result<T> {String code;String msg;T data;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public T getData() {return data;}public void setData(T data) {this.data = data;}}
而我们经常是这么做的 new Result<>() 返回;
@ResponseBody@RequestMapping("/test")public Result<BusinessResult> test() {//模拟业务成返回数据Result<BusinessResult> result = new Result<>();return result;}
这样做看起来好像没有什么不对,我已经通过 Result 封装了我的数据格式,返回去的结果是统一的。
但是我们仔细想想 ,我每个接口,每个Service ,每个业务实现类都要 返回一个 Result 这是不是重复的工作,可不可以统一封装呢?
重复的工作我们都应该想办法避免。
而且再仔细想想 们的业务Service ,注重点是完成我们的业务工作而不是花费大量的时间在 new Result() 上。
这样是三层架构的精髓。每一层都负责不一样的事情,尽可能的处理与自己关注点,避免无干的事情,
Service 的重点就是业务,而封装数据应该由Contrller 完成。
思想很重!!!!
于是我们想办法把他简化,正确的做法应该是这样的:
@ResponseBody@RequestMapping("/test")public BusinessResult test() {//模拟业务成返回数据BusinessResult result = new BusinessResult();return result;}
我们的返回结果应该是我们的业务数据,封装数据 由spring mvc 控制层完成。
HttpMessageConverter 是 Spring3.0 新添加的一个接口,负责将请求信息转换为一个对象(类型为 T),将对象(类型为 T)输出为响应信息。
MappingJackson2HttpMessageConverter ,FastJsonHttpMessageConverter 等都是通过继承
HttpMessageConverter 达到json 转换效果, 有兴趣的同学可以看看源码。
我们也可以利用 重写 MappingJackson2HttpMessageConverter 或 FastJsonHttpMessageConverter 达到我们的 统一数据输出:
/*** Created by Administrator on 2017/6/14.* 全局数据 统一输出*/public class GlobalMessageConverter extends MappingJackson2HttpMessageConverter {public static Logger logger = LoggerFactory.getLogger(GlobalMessageConverter.class);/*** 写出数据** @param object* @param type* @param outputMessage* @throws IOException* @throws HttpMessageNotWritableException*/@Overrideprotected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {//Result 类型的 不用处理if (object instanceof Result ) {super.writeInternal(object, type, outputMessage);return;}Result<Object> baseRes = new Result<>();baseRes.setData(object);baseRes.setMsg("操作成功");baseRes.setCode(0);logger.info("输出参数:" + JsonUtil.toJson(baseRes));super.writeInternal(baseRes, Result.class, outputMessage);}@Overrideprotected void init(ObjectMapper objectMapper) {super.init(objectMapper);getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);}@Overrideprotected boolean supports(Class<?> clazz) {return super.supports(clazz);}@Overridepublic void setSupportedMediaTypes(List<MediaType> supportedMediaTypes) {super.setSupportedMediaTypes(supportedMediaTypes);}}
spring boot 配置 HttpMessageConverter:
@EnableFeignClients@SpringBootApplication@Configuration@EnableEurekaClient@EnableScheduling@EnableHystrixpublic class MicroBlogArticleCommentsServiceApplication {public static void main(String[] args) {SpringApplication.run(MicroBlogArticleCommentsServiceApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}@Beanpublic HttpMessageConverters fastJsonHttpMessageConverters() {GlobalMessageConverter converter = new GlobalMessageConverter();return new HttpMessageConverters(converter);}}
细心的同学可能会发现,如果我发生错误需要返回错误类型的 Result 怎么办? 你这样只能返回正确结果的Result(业务正常的Result),要是业务失败,如密码错误,用户不存在等怎么处理?
Spring mvc Json 的正确返回姿势的更多相关文章
- spring mvc json 返回乱码问题解决(vestion:3.x.x)
本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:<spring mvc json 返回乱码问题解决(vestion:3.x.x)> 工程中用springmvc返 ...
- spring mvc: json练习
spring mvc: json练习 本例需要用到的json包: 如下: jackson-databind jackson-core jackson-annotations <!-- https ...
- Spring MVC JSON自己定义类型转换(续)
前面提到了两种转换类型的方法(Spring MVC JSON自己定义类型转换),这里针对Json转换提供一种更简便的方法. 通过配置全局的日期转换来避免使用麻烦的注解. 首先用到了一个简单的日期工具类 ...
- 160506、Spring mvc新手入门(11)-返回json 字符串的其他方式
Spring MVC返回 json字符串的方式有很多种方法,这里介绍最简单,也是最常使用的两种方式 一.使用 PrintWriter printWriter 直接输出字符串到返回结果中 不需 ...
- Spring MVC全局异常后返回JSON异常数据
问题: 当前项目是作为手机APP后台支持,使用spring mvc + mybaits + shiro进行开发.后台服务与手机端交互是发送JSON数据.如果后台发生异常,会直接返回异常页面,显示异常内 ...
- spring mvc json返回防止乱码
乱码问题 乱码一直是编程的常见问题,spring mvc 返回json数据时可能导致乱码,需要在controller中添加如下代码: @RequestMapping("/test" ...
- [Spring MVC] - JSON
Spring MVC中使用JSON,先必需引用两个包:jackson-core-asl-1.9.13.jar.jackson-mapper-asl-1.9.13.jar 因为需要使用到jquery测试 ...
- Spring MVC json配置
接口类的Controller,一般返回的是json数据,而Spring MVC中默认返回的string,而jsp页面的话,会按配置中自己行匹配转义字符串为对应的jsp文件. @Controller @ ...
- Spring MVC JSON 实现JsonSerializer Date类型转换
转载至:http://blog.csdn.net/lantianzhange/article/details/40920933 在Spring MVC中存在两大类的类型转换,一类是Json,一个是Sp ...
随机推荐
- C++中输出字符到文本文档
#include <iostream> #include <fstream> //ofstream类的头文件 using namespace std; int main() { ...
- [LeetCode&Python] Problem 447. Number of Boomerangs
Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of po ...
- Unity 3D-Canvas画布的三种模式
Unity开发VR之Vuforia 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- ...
- Java中的Arrays类使用详解
首先先创建一个打印数组的方法,方便后面直接使用 public static void output(int []a) { for(int i=0;i<a.length;i++) { System ...
- 移动Web制作——JD案例
1.制作base.css 2.制作index.html 此时会考虑页面的流式布局 3.制作index.css 总结: 1.页面制作时应注意流式布局,各版本的兼容性. 2.页面的大体组成主要有:轮播图. ...
- Spring mvc 导出table到Excel
/** * * @Title: exportExcel * @Description: TODO(导出到excel) * @param Page page * @return ModelAndView ...
- test-ipv6
http://test-ipv6.com/ ! 你的公网 IPv4 地址是 89.42.31.211! 你的公网 IPv6 地址是 2001:ac8:21:8::376e:989b! 你已接入 IPv ...
- Python基础-使用paramiko
一:简介 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 由于使用的是python这样的能够跨平台运行的语言,所以所有python支 ...
- js验证后台传递的map数据是否为空
if(JSON.stringify(data)=='{}'){ $("#year").append("<option>--请选择--</option&g ...
- String的方法capitalize
官方解释:Return a copy of the string with its first character capitalized and the rest lowercased.(返回字符串 ...