• Json和全局异常处理


    目录

    1、SpringMVC对Json的支持

    1.1、Json的各种场景

    1.2、pom依赖

    1.3、Springmvc.xml配置

    1.4、后台代码

    1.4.1、ClazzBiz

    1.4.2、ClazzBizImpl

    1.4.3、ClazzMapper.java

    1.4.4、ClazzMapper.xml

    1.4.5、JsonController

    1.5、前台测试

    1.5.1、Index.jsp

    1.5.2、运行效果

    2、Springmvc的全局异常处理

    2.1、Springmvc自带的简单异常处理器

    2.2、通过HandlerExceptionResovler接口实现全局异常

    2.2.1、GlobalException

    2.2.2、GlobalException

    2.2.3、controller层

    2.3、使用@controllerAdvice+@ExceptionHandler实现全局异常处理

    2.4、全局异常处理Json返回


    1、SpringMVC对Json的支持

    1.1、Json的各种场景

    1. 1.1返回List
    2. 1.2返回List
    3. 1.3返回T
    4. 1.4返回Map
    5. 1.5返回混合
    6. 1.6返回JSON字符串

    1.2、pom依赖

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.core</groupId>
    3. <artifactId>jackson-databind</artifactId>
    4. <version>2.9.3</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>com.fasterxml.jackson.core</groupId>
    8. <artifactId>jackson-core</artifactId>
    9. <version>2.9.3</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>com.fasterxml.jackson.core</groupId>
    13. <artifactId>jackson-annotations</artifactId>
    14. <version>2.9.3</version>
    15. </dependency>

    1.3、Springmvc.xml配置

    1. <!--支持json数据返回的适配器-->
    2. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    3. <property name="messageConverters">
    4. <list>
    5. <ref bean="mappingJackson2HttpMessageConverter"/>
    6. </list>
    7. </property>
    8. </bean>
    9. <bean id="mappingJackson2HttpMessageConverter"
    10. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    11. <!--处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
    12. <property name="supportedMediaTypes">
    13. <list>
    14. <value>text/html;charset=UTF-8</value>
    15. <value>text/json;charset=UTF-8</value>
    16. <value>application/json;charset=UTF-8</value>
    17. </list>
    18. </property>
    19. </bean>

    1.4、后台代码

    1.4.1、ClazzBiz

    1. package com.ssr.ssm2.biz;
    2. import com.ssr.ssm2.model.Clazz;
    3. import com.ssr.ssm2.uitl.PageBean;
    4. import java.util.List;
    5. import java.util.Map;
    6. public interface ClazzBiz {
    7. int deleteByPrimaryKey(Integer cid);
    8. int insert(Clazz record);
    9. int insertSelective(Clazz record);
    10. Clazz selectByPrimaryKey(Integer cid);
    11. List listPager(Clazz clazz, PageBean pageBean);
    12. int updateByPrimaryKeySelective(Clazz record);
    13. int updateByPrimaryKey(Clazz record);
    14. List listMapPager(Clazz clazz, PageBean pageBean);
    15. }

    1.4.2、ClazzBizImpl

    1. package com.ssr.ssm2.biz.impl;
    2. import com.ssr.ssm2.biz.ClazzBiz;
    3. import com.ssr.ssm2.mapper.ClazzMapper;
    4. import com.ssr.ssm2.model.Clazz;
    5. import com.ssr.ssm2.uitl.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. import java.util.Map;
    10. /**
    11. * @author四金
    12. * @site 2261696885
    13. * @company 浪琴湾总公司
    14. * @create 2022-08-17-19:27
    15. */
    16. @Service
    17. public class ClazzBizImpl implements ClazzBiz {
    18. @Autowired
    19. private ClazzMapper clazzMapper;
    20. @Override
    21. public int deleteByPrimaryKey(Integer cid) {
    22. return clazzMapper.deleteByPrimaryKey(cid);
    23. }
    24. @Override
    25. public int insert(Clazz record) {
    26. return clazzMapper.insert(record);
    27. }
    28. @Override
    29. public int insertSelective(Clazz record) {
    30. return clazzMapper.insertSelective(record);
    31. }
    32. @Override
    33. public Clazz selectByPrimaryKey(Integer cid) {
    34. return clazzMapper.selectByPrimaryKey(cid);
    35. }
    36. @Override
    37. public List listPager(Clazz clazz, PageBean pageBean) {
    38. return clazzMapper.listPager(clazz);
    39. }
    40. @Override
    41. public int updateByPrimaryKeySelective(Clazz record) {
    42. return clazzMapper.updateByPrimaryKeySelective(record);
    43. }
    44. @Override
    45. public int updateByPrimaryKey(Clazz record) {
    46. return clazzMapper.updateByPrimaryKey(record);
    47. }
    48. @Override
    49. public List listMapPager(Clazz clazz, PageBean pageBean) {
    50. if(true)
    51. throw new RuntimeException("查询班级信息异常、异常存在于ClazzBizImpl.list方法中");
    52. return clazzMapper.listMapPager(clazz);
    53. }
    54. }

    1.4.3、ClazzMapper.java

    1. package com.ssr.ssm2.mapper;
    2. import com.ssr.ssm2.model.Clazz;
    3. import org.springframework.stereotype.Repository;
    4. import java.util.List;
    5. import java.util.Map;
    6. @Repository
    7. public interface ClazzMapper {
    8. int deleteByPrimaryKey(Integer cid);
    9. int insert(Clazz record);
    10. int insertSelective(Clazz record);
    11. Clazz selectByPrimaryKey(Integer cid);
    12. List listPager(Clazz clazz);
    13. List listMapPager(Clazz clazz);
    14. int updateByPrimaryKeySelective(Clazz record);
    15. int updateByPrimaryKey(Clazz record);
    16. }

    1.4.4、ClazzMapper.xml

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3. <mapper namespace="com.ssr.ssm2.mapper.ClazzMapper" >
    4. <resultMap id="BaseResultMap" type="com.ssr.ssm2.model.Clazz" >
    5. <constructor >
    6. <idArg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    7. <arg column="cname" jdbcType="VARCHAR" javaType="java.lang.String" />
    8. <arg column="cteacher" jdbcType="VARCHAR" javaType="java.lang.String" />
    9. <arg column="pic" jdbcType="VARCHAR" javaType="java.lang.String" />
    10. </constructor>
    11. </resultMap>
    12. <sql id="Base_Column_List" >
    13. cid, cname, cteacher, pic
    14. </sql>
    15. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    16. select
    17. <include refid="Base_Column_List" />
    18. from t_struts_class
    19. where cid = #{cid,jdbcType=INTEGER}
    20. </select>
    21. <select id="listPager" resultType="com.ssr.ssm2.model.Clazz" parameterType="com.ssr.ssm2.model.Clazz" >
    22. select
    23. <include refid="Base_Column_List" />
    24. from t_struts_class
    25. <where>
    26. <if test="cname != null and cname != ''">
    27. and cname like CONCAT('%',#{cname},'%')
    28. </if>
    29. <if test="cid != null and cid != ''">
    30. and cid = #{cid}
    31. </if>
    32. </where>
    33. </select>
    34. <select id="listMapPager" resultType="java.util.Map" parameterType="com.ssr.ssm2.model.Clazz" >
    35. select
    36. <include refid="Base_Column_List" />
    37. from t_struts_class
    38. <where>
    39. <if test="cname != null and cname != ''">
    40. and cname like CONCAT('%',#{cname},'%')
    41. </if>
    42. <if test="cid != null and cid != ''">
    43. and cid = #{cid}
    44. </if>
    45. </where>
    46. </select>
    47. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    48. delete from t_struts_class
    49. where cid = #{cid,jdbcType=INTEGER}
    50. </delete>
    51. <insert id="insert" parameterType="com.ssr.ssm2.model.Clazz" >
    52. insert into t_struts_class (cid, cname, cteacher,
    53. pic)
    54. values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
    55. #{pic,jdbcType=VARCHAR})
    56. </insert>
    57. <insert id="insertSelective" parameterType="com.ssr.ssm2.model.Clazz" >
    58. insert into t_struts_class
    59. <trim prefix="(" suffix=")" suffixOverrides="," >
    60. <if test="cid != null" >
    61. cid,
    62. </if>
    63. <if test="cname != null" >
    64. cname,
    65. </if>
    66. <if test="cteacher != null" >
    67. cteacher,
    68. </if>
    69. <if test="pic != null" >
    70. pic,
    71. </if>
    72. </trim>
    73. <trim prefix="values (" suffix=")" suffixOverrides="," >
    74. <if test="cid != null" >
    75. #{cid,jdbcType=INTEGER},
    76. </if>
    77. <if test="cname != null" >
    78. #{cname,jdbcType=VARCHAR},
    79. </if>
    80. <if test="cteacher != null" >
    81. #{cteacher,jdbcType=VARCHAR},
    82. </if>
    83. <if test="pic != null" >
    84. #{pic,jdbcType=VARCHAR},
    85. </if>
    86. </trim>
    87. </insert>
    88. <update id="updateByPrimaryKeySelective" parameterType="com.ssr.ssm2.model.Clazz" >
    89. update t_struts_class
    90. <set >
    91. <if test="cname != null" >
    92. cname = #{cname,jdbcType=VARCHAR},
    93. </if>
    94. <if test="cteacher != null" >
    95. cteacher = #{cteacher,jdbcType=VARCHAR},
    96. </if>
    97. <if test="pic != null" >
    98. pic = #{pic,jdbcType=VARCHAR},
    99. </if>
    100. </set>
    101. where cid = #{cid,jdbcType=INTEGER}
    102. </update>
    103. <update id="updateByPrimaryKey" parameterType="com.ssr.ssm2.model.Clazz" >
    104. update t_struts_class
    105. set cname = #{cname,jdbcType=VARCHAR},
    106. cteacher = #{cteacher,jdbcType=VARCHAR},
    107. pic = #{pic,jdbcType=VARCHAR}
    108. where cid = #{cid,jdbcType=INTEGER}
    109. </update>
    110. </mapper>

    1.4.5、JsonController

    1. package com.ssr.ssm2.controller;
    2. import com.ssr.ssm2.biz.ClazzBiz;
    3. import com.ssr.ssm2.exception.GlobalException;
    4. import com.ssr.ssm2.model.Clazz;
    5. import com.ssr.ssm2.uitl.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 javax.servlet.http.HttpServletRequest;
    10. import java.util.HashMap;
    11. import java.util.List;
    12. import java.util.Map;
    13. /**
    14. * @author四金
    15. * @site 2261696885
    16. * @company 浪琴湾总公司
    17. * @create 2022-08-22-16:34
    18. */
    19. @Controller
    20. @RequestMapping("/clz/json")
    21. public class JsonController {
    22. @Autowired
    23. private ClazzBiz clazzBiz;
    24. @RequestMapping("/clzEdit")
    25. public String clzEdit(){
    26. System.out.println("JsonController.clzEdit");
    27. return "clzEdit";
    28. }
    29. // list<T>的格式
    30. @RequestMapping("/list")
    31. public List<Clazz> list(HttpServletRequest request,Clazz clazz){
    32. PageBean pageBean = new PageBean();
    33. pageBean.setRequest(request);
    34. if(true)
    35. throw new RuntimeException("查询班级信息异常、异常存在于JsonController.list方法中");
    36. // [{},{}]
    37. return this.clazzBiz.listPager(clazz,pageBean);
    38. }
    39. // list<Map>的格式
    40. @RequestMapping("/listMap")
    41. public List<Map> listMap(HttpServletRequest request, Clazz clazz){
    42. PageBean pageBean = new PageBean();
    43. pageBean.setRequest(request);
    44. // [{},{}]
    45. return this.clazzBiz.listMapPager(clazz,pageBean);
    46. }
    47. // map的格式
    48. @RequestMapping("/map")
    49. public Map map(HttpServletRequest request, Clazz clazz){
    50. PageBean pageBean = new PageBean();
    51. pageBean.setRequest(request);
    52. // [{},{}]
    53. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    54. }
    55. // map的格式
    56. @RequestMapping("/load")
    57. public Clazz load(HttpServletRequest request, Clazz clazz){
    58. // http://localhost:8080/clz/json/load?cid=2
    59. PageBean pageBean = new PageBean();
    60. pageBean.setRequest(request);
    61. if(true)
    62. throw new GlobalException("系统繁忙,请参考E007;");
    63. // [{},{}]
    64. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    65. }
    66. // {
    67. // msg:"",
    68. // code:200,
    69. // data:[]
    70. // pageBean:{}
    71. // }
    72. @RequestMapping("/hunhe")
    73. public Map hunhe(HttpServletRequest request, Clazz clazz){
    74. // http://localhost:8080/clz/json/load?cid=2
    75. PageBean pageBean = new PageBean();
    76. pageBean.setRequest(request);
    77. List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
    78. Map map = new HashMap();
    79. map.put("date",lst);
    80. map.put("pagebean",pageBean);
    81. return map;
    82. }
    83. }

    1.5、前台测试

    1.5.1、Index.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Administrator
    4. Date: 2022/8/22
    5. Time: 17: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>测试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>

    1.5.2、运行效果

     返回list

    返回list

    返回T对象

     

    返回 map对象

     

    返回混合对象

    2、Springmvc的全局异常处理

    2.1、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/22
    5. Time: 19:15
    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. <hr>
    16. ${ex}
    17. </body>
    18. </html>

    2.2、通过HandlerExceptionResovler接口实现全局异常

    2.2.1、GlobalException

    1. package com.ssr.ssm2.exception;
    2. /**
    3. * @author四金
    4. * @site 2261696885
    5. * @company 浪琴湾总公司
    6. * @create 2022-08-22-19:44
    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. }

    2.2.2、GlobalHandlerExceptionResovler 

    1. package com.ssr.ssm2.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四金
    9. * @site 2261696885
    10. * @company 浪琴湾总公司
    11. * @create 2022-08-22-19:28
    12. *
    13. * 处理全局异常的解析器
    14. *
    15. */
    16. //@Component
    17. public class GlobalHandlerExceptionResovler implements HandlerExceptionResolver {
    18. /**
    19. *
    20. * @param httpServletRequest
    21. * @param httpServletResponse
    22. * @param o 目标对象
    23. * @param e 目标对象执行,出现的异常对象
    24. * @return
    25. */
    26. @Override
    27. public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    28. ModelAndView mv = new ModelAndView();
    29. mv.setViewName("error");
    30. if(e instanceof GlobalException){
    31. GlobalException exception = (GlobalException) e;
    32. mv.addObject("ex",exception.getMessage());
    33. mv.addObject("msg","全局异常,错误码501");
    34. }
    35. else if(e instanceof RuntimeException){
    36. RuntimeException exception = (RuntimeException) e;
    37. mv.addObject("ex",exception.getMessage());
    38. mv.addObject("msg","运行时异常,错误码601");
    39. }
    40. return mv;
    41. }
    42. }

    2.2.3、controller层

    1. // T
    2. @ResponseBody
    3. @RequestMapping("/load")
    4. public Clazz load(HttpServletRequest request, Clazz clazz){
    5. // http://localhost:8080/clz/json/load?cid=2
    6. // System.out.println("JsonController.list");
    7. // PageBean pageBean=new PageBean();
    8. // pageBean.setRequest(request);
    9. // {}
    10. if(clazz.getCid()!=null){
    11. List<Clazz> lst=this.clazzBiz.listPager(clazz,null);
    12. if(true)
    13. throw new GlobalException("错误出现在JsonController.load");
    14. return lst.get(0);
    15. }
    16. return null;
    17. }

    2.3、使用@controllerAdvice+@ExceptionHandler实现全局异常处理

    1. package com.ssr.ssm2.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 2261696885
    8. * @company 浪琴湾总公司
    9. * @create 2022-08-22-19:56
    10. */
    11. //@ControllerAdvice
    12. public class GlobalExceptionResolver {
    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","全局异常,GlobalExceptionResolver错误码501");
    21. }
    22. else if(e instanceof RuntimeException){
    23. RuntimeException exception = (RuntimeException) e;
    24. mv.addObject("ex",exception.getMessage());
    25. mv.addObject("msg","运行时异常,GlobalExceptionResolver错误码601");
    26. }
    27. return mv;
    28. }
    29. }

    2.4、全局异常处理Json返回

    1. package com.ssr.ssm2.exception;
    2. import org.springframework.web.bind.annotation.ExceptionHandler;
    3. import org.springframework.web.bind.annotation.RestControllerAdvice;
    4. import org.springframework.web.servlet.ModelAndView;
    5. import java.util.HashMap;
    6. import java.util.Map;
    7. /**
    8. * @author四金
    9. * @site 2261696885
    10. * @company 浪琴湾总公司
    11. * @create 2022-08-22-19:56
    12. *
    13. * 档出现异常,统一想前端响应错误信息的json对象数据
    14. */
    15. @RestControllerAdvice
    16. public class GlobalExceptionResolver2 {
    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","全局异常,GlobalExceptionResolver错误码501");
    24. }
    25. else if(e instanceof RuntimeException){
    26. RuntimeException exception = (RuntimeException) e;
    27. map.put("ex",exception.getMessage());
    28. map.put("msg","运行时异常,GlobalExceptionResolver错误码601");
    29. }
    30. return map;
    31. }
    32. }

    运行结果:

     

  • 相关阅读:
    Ubuntu18.04 realsenseD435i深度摄像头外参标定的问题
    【二十四】springboot使用EasyExcel和线程池实现多线程导入Excel数据
    35【源码】数据可视化:基于 Echarts + Python 动态实时大屏 - 门店销售业绩数据中心
    java-php-net-python-东软健身会员网站计算机毕业设计程序
    数据分析利器---jupyter
    物联网的应用——环境监测
    力扣刷题-数组-双指针法总结-移除元素
    【Linux】安装mysql
    [附源码]java毕业设计学生档案管理系统论文
    IBM MQ 故障诊断(一)
  • 原文地址:https://blog.csdn.net/m0_65774688/article/details/126497100