• JSON和全局异常处理


    目录

    一、json解析

    二、全局异常处理

    1、为什么要用全局异常处理

    2、SpringMVC异常分类

    1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

    2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器

    3)使用@ControllerAdvice + @ExceptionHandler

    三、json统一处理


    一、json解析

    JSON的三种形式:

    ①、{}----->JSON对象

    ②、[]------>JSON数组

    ③、{

                    msg=" ",

                    code=" ",

                    data=[]

            }------>对象数组

    SpringMVC要如果产生上述的三种形式JSON?

    步骤:

    1、导入pom.xml依赖

    2、配置Springmvc.xml适配器

    3、使用注解@responseBody 能够将任何的数据转成json对象

    ①、pom.xml依赖

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.coregroupId>
    3. <artifactId>jackson-databindartifactId>
    4. <version>2.9.3version>
    5. dependency>
    6. <dependency>
    7. <groupId>com.fasterxml.jackson.coregroupId>
    8. <artifactId>jackson-coreartifactId>
    9. <version>2.9.3version>
    10. dependency>
    11. <dependency>
    12. <groupId>com.fasterxml.jackson.coregroupId>
    13. <artifactId>jackson-annotationsartifactId>
    14. <version>2.9.3version>
    15. dependency>

     ②、Springmvc.xml适配器

    1. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    2. <property name="messageConverters">
    3. <list>
    4. <ref bean="mappingJackson2HttpMessageConverter"/>
    5. list>
    6. property>
    7. bean>
    8. <bean id="mappingJackson2HttpMessageConverter"
    9. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    10. <property name="supportedMediaTypes">
    11. <list>
    12. <value>text/html;charset=UTF-8value>
    13. <value>text/json;charset=UTF-8value>
    14. <value>application/json;charset=UTF-8value>
    15. list>
    16. property>
    17. bean>

     ③、后端代码编写

    先编写在ClazzMapper.xml中编写一个查询的方法

    1. <select id="listMapPager" resultType="java.util.Map" parameterType="com.mgy.ssm.model.Clazz" >
    2. select
    3. <include refid="Base_Column_List" />
    4. from t_struts_class
    5. <where>
    6. <if test="cname !=null and cname != ''">
    7. and cname like concat('%',#{cname},'%')
    8. if>
    9. <if test="cid !=null and cid != ''">
    10. and cid=#{cid}
    11. if>
    12. where>
    13. select>

     将listMapPager该方法在ClazzMapper、ClazzBiz和ClazzBizImpl中实现出来,重新创建一个新类

    1. package com.mgy.ssm.controller;
    2. import com.mgy.ssm.biz.ClazzBiz;
    3. import com.mgy.ssm.model.Clazz;
    4. import com.mgy.ssm.util.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.ResponseBody;
    9. import javax.servlet.http.HttpServletRequest;
    10. import java.util.HashMap;
    11. import java.util.List;
    12. import java.util.Map;
    13. /**
    14. * @author 云鹤衫
    15. * @site www.yunheshan.com
    16. * @company xxx公司
    17. * @create  2022-08-22 18:51
    18. */
    19. @Controller
    20. @RequestMapping("/clz/json")
    21. public class JsonController {
    22. @Autowired
    23. private ClazzBiz clazzBiz;
    24. @ResponseBody
    25. @RequestMapping("/clzEdit")
    26. public String clzEdit(){
    27. System.out.println("JsonController.clzEdit");
    28. return "clzEdit";
    29. }
    30. // List
    31. @ResponseBody
    32. @RequestMapping("/list")
    33. public List list(HttpServletRequest req,Clazz clazz){
    34. PageBean pageBean=new PageBean();
    35. pageBean.setRequest(req);
    36. // [{},{}]
    37. return this.clazzBiz.listPager(clazz,pageBean);
    38. }
    39. // List
    40. @ResponseBody
    41. @RequestMapping("/listMap")
    42. public List listMapPager(HttpServletRequest req, Clazz clazz){
    43. PageBean pageBean=new PageBean();
    44. pageBean.setRequest(req);
    45. // [{},{}]
    46. return this.clazzBiz.listMapPager(clazz,pageBean);
    47. }
    48. // List
    49. @ResponseBody
    50. @RequestMapping("/map")
    51. public Map map(HttpServletRequest req, Clazz clazz){
    52. PageBean pageBean=new PageBean();
    53. pageBean.setRequest(req);
    54. // {}
    55. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    56. }
    57. // T
    58. @ResponseBody
    59. @RequestMapping("/load")
    60. public Clazz load(HttpServletRequest req, Clazz clazz){
    61. // http://localhost:8080/clz/json/load?cid=2
    62. PageBean pageBean=new PageBean();
    63. pageBean.setRequest(req);
    64. // {}
    65. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    66. }
    67. /* {
    68. msg:"",
    69. code:200,
    70. data:[],
    71. pageBean:{}
    72. }*/
    73. @ResponseBody
    74. @RequestMapping("/hunhe")
    75. public Map hunhe(HttpServletRequest req, Clazz clazz){
    76. // http://localhost:8080/clz/json/load?cid=2
    77. PageBean pageBean=new PageBean();
    78. pageBean.setRequest(req);
    79. List lst = this.clazzBiz.listPager(clazz, pageBean);
    80. Map map=new HashMap();
    81. map.put("data",lst);
    82. map.put("pagebean",pageBean);
    83. return map;
    84. }
    85. }

     ④、前端代码编写

    index.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Administrator
    4. Date: 2022/8/22
    5. Time: 19:35
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. 测试json数据返回

    效果:

     list方法效果:

     listMap方法效果:

    load方法效果:

    map方法效果:

    hunhe方法效果:

    二、全局异常处理

    1、为什么要用全局异常处理

    2、SpringMVC异常分类

    1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

    在JsonController类上加入@ResController注解

     

    @ResponseBody+@controller=@ResController

    Controller层

    1. @RequestMapping("/list")
    2. public List list(HttpServletRequest req,Clazz clazz){
    3. PageBean pageBean=new PageBean();
    4. pageBean.setRequest(req);
    5. if(true)
    6. throw new RuntimeException("查询班级异常,异常存在于JsonController.list方法中");
    7. // [{},{}]
    8. return this.clazzBiz.listPager(clazz,pageBean);
    9. }
    10. @RequestMapping("/load")
    11. public Clazz load(HttpServletRequest req, Clazz clazz){
    12. // http://localhost:8080/clz/json/load?cid=2
    13. PageBean pageBean=new PageBean();
    14. pageBean.setRequest(req);
    15. if(true)
    16. throw new GlobalException("系统繁忙,请参考E007l;");
    17. // {}
    18. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    19. }

     Service层

    1. @Override
    2. public List listMapPager(Clazz clazz, PageBean pageBean) {
    3. if(true)
    4. throw new RuntimeException("查询班级异常,ClazzBizImpl.list方法中");
    5. return clazzMapper.listMapPager(clazz);
    6. }

    效果:

    点击图上两个方法

     返回list对象效果:

    返回list对象效果:

    2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器

    配置SpringMVC

    1. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    2. <property name="defaultErrorView" value="error"/>
    3. <property name="exceptionAttribute" value="ex"/>
    4. <property name="exceptionMappings">
    5. <props>
    6. <prop key="java.lang.RuntimeException">errorprop>
    7. props>
    8. property>
    9. bean>

     Error.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Administrator
    4. Date: 2022/8/23
    5. Time: 18:25
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <html>
    10. <head>
    11. <title>错误信息页面title>
    12. head>
    13. <body>
    14. ${ex}
    15. body>
    16. html>

    效果:

     

    3)使用@ControllerAdvice + @ExceptionHandler

    先将上面SpringMVC中关于异常处理的配置取消掉

    先建立一个类作为全局异常类

    1. package com.mgy.ssm.exception;
    2. /**
    3. * @author 云鹤衫
    4. * @site www.yunheshan.com
    5. * @company xxx公司
    6. * @create  2022-08-23 18:30
    7. */
    8. public class GlobalException extends RuntimeException{
    9. public GlobalException() {
    10. }
    11. public GlobalException(String message) {
    12. super(message);
    13. }
    14. public GlobalException(String message, Throwable cause) {
    15. super(message, cause);
    16. }
    17. public GlobalException(Throwable cause) {
    18. super(cause);
    19. }
    20. public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    21. super(message, cause, enableSuppression, writableStackTrace);
    22. }
    23. }

     在建立一个类作为异常处理器

    1. package com.mgy.ssm.exception;
    2. import org.springframework.web.bind.annotation.ControllerAdvice;
    3. import org.springframework.web.bind.annotation.ExceptionHandler;
    4. import org.springframework.web.servlet.ModelAndView;
    5. /**
    6. * @author 云鹤衫
    7. * @site www.yunheshan.com
    8. * @company xxx公司
    9. * @create  2022-08-23 19:09
    10. */
    11. @ControllerAdvice
    12. public class GlobalExceptionHandler {
    13. @ExceptionHandler
    14. public ModelAndView handler(Exception e){
    15. ModelAndView mv=new ModelAndView();
    16. mv.setViewName("error");
    17. if(e instanceof GlobalException){
    18. GlobalException exception=(GlobalException)e;
    19. mv.addObject("ex",exception.getMessage());
    20. mv.addObject("msg","全局异常,GlobalExceptionHandler,错误码501");
    21. }else if(e instanceof RuntimeException){
    22. RuntimeException exception=(RuntimeException)e;
    23. mv.addObject("ex",exception.getMessage());
    24. mv.addObject("msg","运行时异常,GlobalExceptionHandler,错误码601");
    25. }
    26. return mv;
    27. }
    28. }

      效果:

     

    三、json统一处理

    将之前异常处理器上的注解注销

    然后重新建立一个异常处理器

    1. package com.mgy.ssm.exception;
    2. import org.springframework.web.bind.annotation.ControllerAdvice;
    3. import org.springframework.web.bind.annotation.ExceptionHandler;
    4. import org.springframework.web.servlet.ModelAndView;
    5. import java.util.HashMap;
    6. import java.util.Map;
    7. /**
    8. * @author 云鹤衫
    9. * @site www.yunheshan.com
    10. * @company xxx公司
    11. * @create  2022-08-23 19:09
    12. *
    13. * 当出现异常,统一向前端响应错误信息的json对象数据
    14. */
    15. //@ControllerAdvice
    16. public class GlobalExceptionHandler2 {
    17. @ExceptionHandler
    18. public Map handler(Exception e){
    19. Map map=new HashMap();
    20. if(e instanceof GlobalException){
    21. GlobalException exception=(GlobalException)e;
    22. map.put("ex",exception.getMessage());
    23. map.put("msg","全局异常,GlobalExceptionHandler,错误码501");
    24. }else if(e instanceof RuntimeException){
    25. RuntimeException exception=(RuntimeException)e;
    26. map.put("ex",exception.getMessage());
    27. map.put("msg","运行时异常,GlobalExceptionHandler,错误码601");
    28. }
    29. return map;
    30. }
    31. }

    效果:

     

  • 相关阅读:
    VirtualBox配置共享文件夹,如果你一直安装增强功能失败,又没有尝试过改内核版本。。。
    [数学建模]---1.层次分析法matlab&python
    从迷之自信到逻辑自信(简版)
    数据库迭代模型扩展
    虾皮规模毁约、毁 offer,操作太离谱了...
    【Leetcode】 406. 根据身高重建队列
    CTFshow_MISC入门_图片篇(基础操作&信息附加)wp
    aac转化为mp3,详细的转换步骤
    《中国垒球》:棍网球委员会·垒球联盟
    【Vuex】状态管理机制
  • 原文地址:https://blog.csdn.net/m0_62604616/article/details/126489975