• SpringMVC 04(JSON和全局异常处理)


    目录

    一,SpringMVC对JSON的支持            

    二,SpringMVC 的全局异常处理


    一,SpringMVC对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>

    后台代码:

    1. package com.ruojuan.ssm.web;
    2. import com.ruojuan.ssm.Exception.GlobalException;
    3. import com.ruojuan.ssm.biz.ClazzBiz;
    4. import com.ruojuan.ssm.model.Clazz;
    5. import com.ruojuan.ssm.util.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Controller;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.ResponseBody;
    10. import javax.servlet.http.HttpServletRequest;
    11. import java.util.HashMap;
    12. import java.util.List;
    13. import java.util.Map;
    14. /**
    15. * @author ruojuan
    16. * @site 123456999
    17. * @company 玉渊工作室
    18. * @create 2022-08-22 16:25
    19. */
    20. @ResponseBody
    21. @Controller
    22. @RequestMapping("/clz/json")
    23. public class JsonController {
    24. @Autowired
    25. private ClazzBiz clazzBiz;
    26. /**
    27. * 返回List
    28. * @param req
    29. * @param clazz
    30. * @return
    31. */
    32. @RequestMapping("/list")
    33. public List list(HttpServletRequest req, Clazz clazz){
    34. PageBean pageBean = new PageBean();
    35. pageBean.setRequest(req);
    36. if(true) {
    37. throw new RuntimeException("查询班级信息异常,异常存在于JsonController.list方法");
    38. }
    39. List lst = this.clazzBiz.listPager(clazz, pageBean);
    40. return lst;
    41. }
    42. /**
    43. * 返回T
    44. * @param req
    45. * @param clazz
    46. * @return
    47. */
    48. /*@RequestMapping("/load")
    49. public Clazz load(HttpServletRequest req, Clazz clazz){
    50. PageBean pageBean = new PageBean();
    51. pageBean.setRequest(req);
    52. if(true){
    53. throw new GlobalException("系统繁忙,请参考E007;");
    54. }
    55. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    56. }*/
    57. @RequestMapping("/load")
    58. public Clazz load(HttpServletRequest req, Clazz clazz){
    59. if(clazz.getCid() != null){
    60. List lst = this.clazzBiz.listPager(clazz, null);
    61. if (true)
    62. throw new GlobalException("错误出现在 JsonController.load...");
    63. return lst.get(0);
    64. }
    65. return null;
    66. }
    67. /**
    68. * 返回List
    69. * @param req
    70. * @param clazz
    71. * @return
    72. */
    73. @RequestMapping("/mapList")
    74. public List mapList(HttpServletRequest req, Clazz clazz){
    75. PageBean pageBean = new PageBean();
    76. pageBean.setRequest(req);
    77. List lst = this.clazzBiz.listMapPager(clazz, pageBean);
    78. return lst;
    79. }
    80. /**
    81. * 返回Map
    82. * @param req
    83. * @param clazz
    84. * @return
    85. */
    86. @RequestMapping("/mapLoad")
    87. public Map mapLoad(HttpServletRequest req, Clazz clazz){
    88. if(clazz.getCid() != null){
    89. List lst = this.clazzBiz.listMapPager(clazz, null);
    90. return lst.get(0);
    91. }
    92. return null;
    93. }
    94. @RequestMapping("/all")
    95. public Map all(HttpServletRequest req, Clazz clazz){
    96. PageBean pageBean = new PageBean();
    97. pageBean.setRequest(req);
    98. List lst = this.clazzBiz.listPager(clazz, pageBean);
    99. Map map = new HashMap();
    100. map.put("lst",lst);
    101. map.put("pageBean",pageBean);
    102. return map;
    103. }
    104. @RequestMapping("/jsonStr")
    105. public String jsonStr(HttpServletRequest req, Clazz clazz){
    106. return "Edit";
    107. }
    108. }

    servic层 :

    1. public List mapListPager(Clazz clazz,PageBean pageBean) {
    2. return clazzMapper.mapListPager(clazz);
    3. }

     Mapper.xml

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

    测试:

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Administrator
    4. Date: 2022/8/22
    5. Time: 16:46
    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<T>对象a><hr>
    15. <a href="${pageContext.request.contextPath}/clz/json/mapList">返回list<Map>对象a><hr>
    16. <a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回T对象a><hr>
    17. <a href="${pageContext.request.contextPath}/clz/json/mapLoad?cid=1">返回Map对象a><hr>
    18. <a href="${pageContext.request.contextPath}/clz/json/all">返回混合对象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

    JsonController :

    1. /**
    2. * 返回List
    3. * @param req
    4. * @param clazz
    5. * @return
    6. */
    7. @ResponseBody
    8. @RequestMapping("/list")
    9. public List list(HttpServletRequest req, Clazz clazz){
    10. PageBean pageBean = new PageBean();
    11. pageBean.setRequest(req);
    12. if(true) {
    13. throw new RuntimeException("查询班级信息异常,异常存在于JsonController.list方法");
    14. }
    15. List lst = this.clazzBiz.listPager(clazz, pageBean);
    16. return lst;
    17. }
    18. /**
    19. * 返回List
    20. * @param req
    21. * @param clazz
    22. * @return
    23. */
    24. @ResponseBody
    25. @RequestMapping("/mapList")
    26. public List mapList(HttpServletRequest req, Clazz clazz){
    27. PageBean pageBean = new PageBean();
    28. pageBean.setRequest(req);
    29. List lst = this.clazzBiz.listMapPager(clazz, pageBean);
    30. return lst;
    31. }

    Bizimpl:

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

    效果: 

     

    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>

    error.jsp

    ${ex}

     

     

      4. 通过HandlerExceptionResovler接口实现全局异常

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

    全局异常GlobalException.java:

            

    1. package com.ruojuan.ssm.Exception;
    2. /**
    3. * @author ruojuan
    4. * @site 123456999
    5. * @company 玉渊工作室
    6. * @create 2022-08-22 17:16
    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.ruojuan.ssm.Exception;
    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 ruojuan
    9. * @site 123456999
    10. * @company 玉渊工作室
    11. * @create 2022-08-22 17:52
    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,
    27. HttpServletResponse httpServletResponse,
    28. Object o, Exception e) {
    29. ModelAndView mv = new ModelAndView();
    30. mv.setViewName("error");
    31. if (e instanceof GlobalException){
    32. GlobalException globalException = (GlobalException) e;
    33. mv.addObject("ex",globalException.getMessage());
    34. mv.addObject("msg","全局异常,错误码501....");
    35. }else if (e instanceof RuntimeException){
    36. RuntimeException runtimeException = (RuntimeException) e;
    37. mv.addObject("ex",runtimeException.getMessage());
    38. mv.addObject("msg","运行时异常,错误码601....");
    39. }
    40. return mv;
    41. }
    42. }

    测试代码Controller层的改变

    1. @ResponseBody
    2. @RequestMapping("/load")
    3. public Clazz load(HttpServletRequest req, Clazz clazz){
    4. if(clazz.getCid() != null){
    5. List lst = this.clazzBiz.listPager(clazz, null);
    6. if (true)
    7. throw new GlobalException("错误出现在 JsonController.load...");
    8. return lst.get(0);
    9. }
    10. return null;
    11. }

     

     使用@ControllerAdvice+@ExceptionHandler实现全局异常

    1. package com.ruojuan.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 ruojuan
    7. * @site 123456999
    8. * @company 玉渊工作室
    9. * @create 2022-08-22 18:10
    10. */
    11. //@ControllerAdvice
    12. public class GlobalExceptionResovler {
    13. @ExceptionHandler
    14. public ModelAndView handler(Exception e){
    15. ModelAndView mv = new ModelAndView();
    16. mv.setViewName("error");
    17. if (e instanceof GlobalException){
    18. GlobalException globalException = (GlobalException) e;
    19. mv.addObject("ex",globalException.getMessage());
    20. mv.addObject("msg","全局异常....");
    21. }else if (e instanceof RuntimeException){
    22. RuntimeException runtimeException = (RuntimeException) e;
    23. mv.addObject("ex",runtimeException.getMessage());
    24. mv.addObject("msg","运行时异常....");
    25. }
    26. return mv;
    27. }
    28. }

     全局异常处理JSON返回

    1. package com.ruojuan.ssm.Exception;
    2. import org.springframework.web.bind.annotation.ControllerAdvice;
    3. import org.springframework.web.bind.annotation.ExceptionHandler;
    4. import org.springframework.web.bind.annotation.RestControllerAdvice;
    5. import java.util.HashMap;
    6. import java.util.Map;
    7. /**
    8. * @author ruojuan
    9. * @site 123456999
    10. * @company 玉渊工作室
    11. * @create 2022-08-22 18:11
    12. *
    13. * 当出现异常,统一向前端响应错误后出现的结果
    14. */
    15. //@ControllerAdvice
    16. @RestControllerAdvice
    17. public class GlobalExceptionJsonResolver {
    18. @ExceptionHandler
    19. public Map handler(Exception e){
    20. Map map = new HashMap();
    21. if (e instanceof GlobalException){
    22. GlobalException globalException = (GlobalException) e;
    23. map.put("ex",globalException.getMessage());
    24. map.put("msg","全局异常 GlobalExceptionResolver,错误码501....");
    25. }else if (e instanceof RuntimeException){
    26. RuntimeException runtimeException = (RuntimeException) e;
    27. map.put("ex",runtimeException.getMessage());
    28. map.put("msg","运行时异常 GlobalExceptionResolver,错误码601....");
    29. }
    30. return map;
    31. }
    32. }

     

  • 相关阅读:
    计算机网络期末复习——简明扼要介绍考点及相关知识
    基于JAVA鞍山丘比特房屋租赁管理系统计算机毕业设计源码+系统+lw文档+部署
    echarts快速实现迁徙地图
    flash attention的CUDA编程和二维线程块实现softmax
    《树莓派4B家庭服务器搭建指南》第二十一期:安装开源远程桌面服务rustdesk, 内网丝滑,外网流畅控制
    docker安装postgresql
    使用selenium/drissionpage时如何阻止chrome自动跳转http到https
    nvm安装及使用
    python 基于flask实现的sse 修改eventstream中类型字段
    linux 配置安装node.js
  • 原文地址:https://blog.csdn.net/weixin_67338832/article/details/126471541