• JSON和全局异常处理


    目录

    一:SpringMVC对JSON的支持

    1.JSON的各种类型

    1.1返回list

    2.代码段 

    3.测试 

    效果图 

    二:SpringMVC的全局异常处理

    1.为什么要全局处理

    2.异常处理思路

     3.SpringMVC异常分类 

    案例:

    1.SpringMVC自带的简单异常处理器

    ​编辑     2:HandlerExceptionResovler接口实现全局异常 

    3.ControllerAdvice+@ExceptionHandler实现全局异常 

    4.全局异常+响应封装类 


    一:SpringMVC对JSON的支持

    1.JSON的各种类型

    1.1返回list

    1. //list
    2. @RequestMapping("/list")
    3. public List<Clazz> list(HttpServletRequest request,Clazz clazz){
    4. PageBean pageBean =new PageBean();
    5. pageBean.setRequest(request);
    6. if(true)
    7. throw new RuntimeException("查询班级信息异常,异常存在于JsonController。list");
    8. return this.classBiz.listPager(clazz,pageBean);
    9. }

    1.2返回list

    1. //list
    2. @RequestMapping("/listMap")
    3. public List<Map> listMap(HttpServletRequest request, Clazz clazz){
    4. PageBean pageBean =new PageBean();
    5. pageBean.setRequest(request);
    6. return this.classBiz.listMapPager(clazz,pageBean);
    7. }

    1.3返回T

    1. @RequestMapping("/load")
    2. public Clazz load(HttpServletRequest request, Clazz clazz){
    3. PageBean pageBean =new PageBean();
    4. pageBean.setRequest(request);
    5. if(true)
    6. throw new GlobalException("系统繁忙,请参考E007");
    7. return this.classBiz.listPager(clazz,pageBean).get(0);
    8. }

    1.4返回Map

    1. // Map
    2. @RequestMapping("/map")
    3. public Map map(HttpServletRequest request, Clazz clazz){
    4. PageBean pageBean =new PageBean();
    5. pageBean.setRequest(request);
    6. return this.classBiz.listMapPager(clazz,pageBean).get(0);
    7. }

    1.5返回混合

    1. @RequestMapping("/hunhe")
    2. public Map hunhe(HttpServletRequest request, Clazz clazz){
    3. PageBean pageBean =new PageBean();
    4. pageBean.setRequest(request);
    5. List<Clazz> lst= this.classBiz.listPager(clazz,pageBean);
    6. Map map = new HashMap();
    7. map.put("data",lst);
    8. map.put("pagebean",pageBean);
    9. return map;
    10. }

    2.代码段 

    导入pom依赖

    1. <!--用来springMVC支持json数据转换-->
    2. <dependency>
    3. <groupId>com.fasterxml.jackson.core</groupId>
    4. <artifactId>jackson-databind</artifactId>
    5. <version>2.9.3</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>com.fasterxml.jackson.core</groupId>
    9. <artifactId>jackson-core</artifactId>
    10. <version>2.9.3</version>
    11. </dependency>
    12. <dependency>
    13. <groupId>com.fasterxml.jackson.core</groupId>
    14. <artifactId>jackson-annotations</artifactId>
    15. <version>2.9.3</version>
    16. </dependency>

    ClazzMapper.xml

    1. <select id="listMapPager" resultType="java.util.Map" parameterType="com.zhoujuan.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>

    ClazzMapper.java

     List listMapPager(Clazz clazz);

    ClazzBiz

    List listMapPager(Clazz clazz, PageBean pageBean);

    3.测试 

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: zjjt
    4. Date: 2022-8-22
    5. Time: 17:09
    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>测试json返回</title>
    12. </head>
    13. <body>
    14. <a href="${pageContext.request.contextPath}/clz/json/list">返回list&lt;T&gt;对象</a><hr>
    15. <a href="${pageContext.request.contextPath}/clz/json/listMap">返回list&lt;Map&gt;对象</a><hr>
    16. <a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回T对象</a><hr>
    17. <a href="${pageContext.request.contextPath}/clz/json/map?cid=1">返回Map对象</a><hr>
    18. <a href="${pageContext.request.contextPath}/clz/json/hunhe">返回混合对象</a><hr>
    19. </body>
    20. </html>

    效果图 

     

    二:SpringMVC的全局异常处理

    1.为什么要全局处理

     我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护

    2.异常处理思路

    系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。

     3.SpringMVC异常分类 

    1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver; 
       2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;
       3)使用@ControllerAdvice + @ExceptionHandler

    案例:

    1.SpringMVC自带的简单异常处理器

    SpringMVC_Servlet.xml配置文件

    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>

     

      
       2:HandlerExceptionResovler接口实现全局异常 

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

     

     

    3.ControllerAdvice+@ExceptionHandler实现全局异常 

    GlobalException

    1. package com.zhoujuan.ssm.excetion;
    2. /**
    3. * @author zhuojuan
    4. * @site www.zhoujuan.com
    5. * @company 玉渊工作室
    6. * @create  2022-08-22 18:21
    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. }

    GlobalHandlerExceptionResovler 

    1. package com.zhoujuan.ssm.excetion;
    2. import org.springframework.stereotype.Component;
    3. import org.springframework.web.servlet.HandlerExceptionResolver;
    4. import org.springframework.web.servlet.ModelAndView;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. /**
    8. * @author zhuojuan
    9. * @site www.zhoujuan.com
    10. * @company 玉渊工作室
    11. * @create  2022-08-22 18:27
    12. *
    13. * 处理全局异常的解析器
    14. */
    15. @Component
    16. public class GlobalHandlerExceptionResovler implements HandlerExceptionResolver {
    17. /**
    18. *
    19. * @param httpServletRequest
    20. * @param httpServletResponse
    21. * @param o 目标对象
    22. * @param e 目标对象执行,出现的异常对象
    23. * @return
    24. */
    25. @Override
    26. public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    27. ModelAndView mv = new ModelAndView();
    28. mv.setViewName("error");
    29. if(e instanceof GlobalException){
    30. GlobalException exception = (GlobalException) e;
    31. mv.addObject("ex",exception.getMessage());
    32. mv.addObject("msg","全局异常,错误码501");
    33. }else if(e instanceof GlobalException){
    34. RuntimeException exception = (RuntimeException) e;
    35. mv.addObject("ex",exception.getMessage());
    36. mv.addObject("msg","运行时异常,错误码601");
    37. }
    38. return mv;
    39. }
    40. }
    1. @Override
    2. public List<Map> listMapPager(Clazz clazz, PageBean pageBean) {
    3. if(true)
    4. throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.list");
    5. return clazzMapper.listMapPager(clazz);
    6. }

     error.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: zjjt
    4. Date: 2022-8-22
    5. Time: 18:14
    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. ${msg}
    15. ${ex}
    16. </body>
    17. </html>

    4.全局异常+响应封装类 

     GlobalExceptionResovler 

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

    GlobalExceptionResovler 2

    1. package com.zhoujuan.ssm.excetion;
    2. import org.springframework.web.bind.annotation.ExceptionHandler;
    3. import org.springframework.web.bind.annotation.RestControllerAdvice;
    4. import java.util.HashMap;
    5. import java.util.Map;
    6. /**
    7. * @author zhuojuan
    8. * @site www.zhoujuan.com
    9. * @company 玉渊工作室
    10. * @create  2022-08-22 18:44
    11. *
    12. * 当出现异常,统一向前端响应错误信息的json对象数据
    13. */
    14. //@ControllerAdvice
    15. @RestControllerAdvice
    16. public class GlobalExceptionResovler2 {
    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","全局异常,错误码501");
    24. }else if(e instanceof GlobalException){
    25. RuntimeException exception = (RuntimeException) e;
    26. map.put("ex",exception.getMessage());
    27. map.put("msg","运行时异常,错误码601");
    28. }
    29. return map;
    30. }
    31. }

  • 相关阅读:
    转铁蛋白修饰蛇床子素长循环脂质体/负载三七皂苷R1的PEG-PLGA纳米粒(R1@Tf-PEG-PLGA NPs)
    基于JAVA社区疫情防控系统设计与实现 毕业设计开题报告
    6.每天进步一点点---Python爬虫urllib库
    JAVA计算机毕业设计在线专业培养方案系统Mybatis+源码+数据库+lw文档+系统+调试部署
    【535. TinyURL 的加密与解密】
    antd-React Table 中文转化
    提高开发质量的 5 个必要实践
    2022 极术通讯-《服务器应用场景性能测试方法 虚拟化》解读
    Empty suite
    云上本地化运营,东非第一大电商平台Kilimall的出海经
  • 原文地址:https://blog.csdn.net/m0_67864917/article/details/126472015