博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMvc-HandlerExceptionResolver
阅读量:4304 次
发布时间:2019-05-27

本文共 1706 字,大约阅读时间需要 5 分钟。

本文描述了当系统内部错误时,如何把JSON对象返回给前台

1.pom文件引用fastJson2.xml文件中配置
3.JAVA代码,必须且只要实现HandlerExceptionResolver类import com.alibaba.fastjson.support.spring.FastJsonJsonView;public class ExceptionResolver implements HandlerExceptionResolver { public static final long serialVersionUID = 1L; @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); FastJsonJsonView view = new FastJsonJsonView(); Map
attributes = new HashMap
(); attributes.put("msg", "随便写点什么"); attributes.put("resultCode", "系统错误"); view.setAttributesMap(attributes); mv.setView(view); return mv; }}

追加:不使用fastjson

因为fastjson是继承了AbstractView,所以自己定义一个类V extends AbstractView也可以,然后重写AbstractView的抽象方法renderMergedOutputModel
方法体里这样实现

@Overrideprotected void renderMergedOutputModel(Map
model,HttpServletRequest request,HttpServletResponse response) throws Exception{ //创建给前端返回的字符串 String aa="{\"msg\":\"系统异常\"}"; ServletOutputStream out=response.getOutputStream(); out.write(aa.getBytes()); out.flush(); out.close();}

这样直接mv.setView(V);当项目出异常的时候,前端就直接显示msg:系统异常了

更简单直接的方法:直接将上述renderMergedOutputModel方法内的内容,挪动到resolveException中,这样也不用创建AbstractView的子类了

@Override	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,			Exception ex) {
String aa="{\"msg\":\"系统异常\"}"; ServletOutputStream out=response.getOutputStream(); out.write(aa.getBytes()); out.flush(); out.close(); return new ModelAndView(); }

本文的方式使用了最底层的request和response,而你可以使用更简洁的方式,可以参考我的文章,但是你需要注意ExceptionHandler无法获取request和response,相对来说失去了灵活性,带来了便利性

转载地址:http://pvhws.baihongyu.com/

你可能感兴趣的文章
suse如何创建定时任务?
查看>>
suse搭建ftp服务器方法
查看>>
centos虚拟机设置共享文件夹并通过我的电脑访问[增加smbd端口修改]
查看>>
文件拷贝(IFileOperation::CopyItem)
查看>>
MapReduce的 Speculative Execution机制
查看>>
大数据学习之路------借助HDP SANDBOX开始学习
查看>>
Hadoop基础学习:基于Hortonworks HDP
查看>>
为什么linux安装程序 都要放到/usr/local目录下
查看>>
Hive安装前扫盲之Derby和Metastore
查看>>
永久修改PATH环境变量的几种办法
查看>>
大数据学习之HDP SANDBOX开始学习
查看>>
Hive Beeline使用
查看>>
Centos6安装图形界面(hdp不需要,hdp直接从github上下载数据即可)
查看>>
CentOS7 中把yum源更换成163源
查看>>
关于yum Error: Cannot retrieve repository metadata (repomd.xml) for repository:xxxxxx.
查看>>
linux下载github中的文件
查看>>
HDP Sandbox里面git clone不了数据(HTTP request failed)【目前还没解决,所以hive的练习先暂时搁置了】
查看>>
动态分区最佳实践(一定要注意实践场景)
查看>>
HIVE—索引、分区和分桶的区别
查看>>
Hive进阶总结(听课总结)
查看>>