本文共 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(Mapmodel,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/