1.根据不同的请求方式,返回页面或json数据
1).创建统一权限异常处理类,所有的权限异常走一个端口
2).根据请求方式不同返回不同数据,页面请求返回403未授权页面,ajax请求返回json数据
package com.cc8w.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class MyExceptionAdvice { @ExceptionHandler(Exception.class) public ModelAndView showInfoE(Exception e, HttpServletRequest request){ if (isAjaxRequest(request)) { ModelAndView modelAndView=new ModelAndView(new MappingJackson2JsonView()); modelAndView.addObject(AjaxResult.authError("错误1")); return modelAndView; //return new ModelAndView(AjaxResult.authError("您没有权限查看该数据").toString()); } else { return new ModelAndView("error1"); } } /** * 是否是Ajax异步请求 * @param request */ public static boolean isAjaxRequest(HttpServletRequest request) { String accept = request.getHeader("accept"); if (accept != null && accept.indexOf("application/json") != -1) { return true; } String xRequestedWith = request.getHeader("X-Requested-With"); if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) { return true; } String uri = request.getRequestURI(); if (isContainStrs(uri, ".json", ".xml")) { return true; } String ajax = request.getParameter("__ajax"); if (isContainStrs(ajax, "json", "xml")) { return true; } return false; } public static boolean isContainStrs(String str, String... strs) { if (str != null && strs != null) { for (String s : strs) { if (str.equalsIgnoreCase(s.trim())) { return true; } } } return false; } }
其中:AjaxResult.authError是系统自定义的json通用返回对象,包含code、msg、data等通用字段自己可以自定义设置。
主要涉及到ModelAndView、MappingJackson2JsonView 通过传入的类型来控制是页面ORjson字符串
2.返回统一的数据结果
https://blog.csdn.net/zhangzengxiu/article/details/121622103
转:
https://blog.csdn.net/butioy_org/article/details/78718405
https://blog.csdn.net/s1040342522/article/details/123545878
https://www.cnblogs.com/chenzhubing/p/11438902.html
https://blog.csdn.net/weixin_56644618/article/details/127580941
标签:return,String,spring,request,错误码,json,mvc,import,ModelAndView From: https://www.cnblogs.com/fps2tao/p/16982700.html