• JOSN和全局异常处理


    目录

    一、SpringMVC对JSON的支持

    1、josn的形式

    2、SpringMVC框架如何生产上述三种格式的数据

    3、导入pom依赖

    4、Springmvc.xml配置

    5、后台代码

    ClazzMapper.java

    ClazzMapper.xml

    JsonController

    6、前台代码

    7、运行

    8、优化:

     二、SpringMVC 的全局异常处理

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

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

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

    4、json的通统一异常处理


    一、SpringMVC对JSON的支持

    1、josn的形式

    {}->json对象
    []->json数组
    {
        msg:"",
        code:200,
        data:[]
    }->json混合对象

    2、SpringMVC框架如何生产上述三种格式的数据

    1.导入pom依赖      Jackson
    2.配置SpringMVC.xml 配置适配器
        作用是做json数据转换的
    3.使用注解@responseBody 能够将任何的数据转成json对象

    3、导入pom依赖

    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>

    4、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>

    5、后台代码

    ClazzBiz

    1. package com.zking.ssm.biz;
    2. import com.zking.ssm.model.Clazz;
    3. import com.zking.ssm.util.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. int updateByPrimaryKeySelective(Clazz record);
    12. int updateByPrimaryKey(Clazz record);
    13. List listPager(Clazz clazz, PageBean pageBean);
    14. List listMapPager(Clazz clazz, PageBean pageBean);
    15. }

    ClazzBizImpl

    1. package com.zking.ssm.impl;
    2. import com.zking.ssm.biz.ClazzBiz;
    3. import com.zking.ssm.mapper.ClazzMapper;
    4. import com.zking.ssm.model.Clazz;
    5. import com.zking.ssm.util.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 3185579318
    13. * @company xxx公司
    14. * @create  2022-08-18 23:34
    15. */
    16. @Service
    17. public class ClassBizImpl 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.insertSelective(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 int updateByPrimaryKeySelective(Clazz record) {
    38. return clazzMapper.updateByPrimaryKeySelective(record);
    39. }
    40. @Override
    41. public int updateByPrimaryKey(Clazz record) {
    42. return clazzMapper.updateByPrimaryKey(record);
    43. }
    44. @Override
    45. public List listPager(Clazz clazz, PageBean pageBean) {
    46. return clazzMapper.listPager(clazz);
    47. }
    48. @Override
    49. public List listMapPager(Clazz clazz, PageBean pageBean) {
    50. return clazzMapper.listMapPager(clazz);
    51. }
    52. }

    ClazzMapper.java

    1. package com.zking.ssm.mapper;
    2. import com.zking.ssm.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. }

    ClazzMapper.xml

    1. "1.0" encoding="UTF-8" ?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3. <mapper namespace="com.zking.ssm.mapper.ClazzMapper" >
    4. <resultMap id="BaseResultMap" type="com.zking.ssm.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.zking.ssm.model.Clazz" parameterType="com.zking.ssm.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 cname = #{cid}
    31. if>
    32. where>
    33. select>
    34. <select id="listMapPager" resultType="java.util.Map" parameterType="com.zking.ssm.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.zking.ssm.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.zking.ssm.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.zking.ssm.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.zking.ssm.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>

    JsonController

    1. package com.zking.ssm.controller;
    2. import com.zking.ssm.biz.ClazzBiz;
    3. import com.zking.ssm.model.Clazz;
    4. import com.zking.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 3185579318
    16. * @company xxx公司
    17. * @create  2022-08-22 16:56
    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 request,Clazz clazz){
    34. PageBean pageBean = new PageBean();
    35. pageBean.setRequest(request);
    36. // [{},{}]
    37. return this.clazzBiz.listPager(clazz,pageBean);
    38. }
    39. // List
    40. @ResponseBody
    41. @RequestMapping("/listMap")
    42. public List listMap(HttpServletRequest request, Clazz clazz){
    43. PageBean pageBean = new PageBean();
    44. pageBean.setRequest(request);
    45. // [{},{}]
    46. return this.clazzBiz.listMapPager(clazz,pageBean);
    47. }
    48. // Map
    49. @ResponseBody
    50. @RequestMapping("/map")
    51. public Map map(HttpServletRequest request, Clazz clazz){
    52. PageBean pageBean = new PageBean();
    53. pageBean.setRequest(request);
    54. // {}
    55. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    56. }
    57. // T
    58. @ResponseBody
    59. @RequestMapping("/load")
    60. public Map load(HttpServletRequest request, Clazz clazz){
    61. // http//localhost:8080/clz/json/load?cid=2
    62. PageBean pageBean = new PageBean();
    63. pageBean.setRequest(request);
    64. // {}
    65. return this.clazzBiz.listMapPager(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 request, Clazz clazz){
    76. // http//localhost:8080/clz/json/load?cid=2
    77. PageBean pageBean = new PageBean();
    78. pageBean.setRequest(request);
    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. }

    6、前台代码

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Administrator
    4. Date: 2022/8/23
    5. Time: 19:45
    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/listMap">返回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/map?cid=1">返回Map对象a><hr>
    18. <a href="${pageContext.request.contextPath}/clz/json/hunhe">返回混合对象a><hr>
    19. body>
    20. html>

    7、运行

     list

     list

     T

     Map

     混合

    8、优化:

    @ResponseBody+@Controller=@restController

     二、SpringMVC 的全局异常处理

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

    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: 21:22
    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>

    list

    list

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

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

    GlobalException.java
    1. package com.zking.ssm.exception;
    2. /**
    3. * @author 白未
    4. * @site 3185579318
    5. * @company xxx公司
    6. * @create  2022-08-23 21:45
    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. }

    GlobalExceptionHandler.java

    1. package com.zking.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 白未
    9. * @site 3185579318
    10. * @company xxx公司
    11. * @create  2022-08-23 21:48
    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",null);
    32. mv.addObject("msg","全局异常,错误码520");
    33. }else if(e instanceof GlobalException) {
    34. GlobalException exception = (GlobalException) e;
    35. mv.addObject("ex", null);
    36. mv.addObject("msg", "运行时异常,错误码666");
    37. }
    38. return mv;
    39. }
    40. }

    controller层

    1. @RequestMapping("/load")
    2. public Map load(HttpServletRequest request, Clazz clazz){
    3. // http//localhost:8080/clz/json/load?cid=2
    4. PageBean pageBean = new PageBean();
    5. pageBean.setRequest(request);
    6. if(true)
    7. throw new GlobalException("系统繁忙,请参考曾超sb");
    8. // {}
    9. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    10. }

    运行

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

    GlobalExceptionResolver
    1. package com.zking.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 3185579318
    8. * @company xxx公司
    9. * @create  2022-08-23 22: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","系统繁忙");
    20. mv.addObject("msg","全局异常 GlobalExceptionResolver,错误码520");
    21. }else if(e instanceof GlobalException) {
    22. GlobalException exception = (GlobalException) e;
    23. mv.addObject("ex", null);
    24. mv.addObject("msg", "运行时异常 GlobalExceptionResolver,错误码666");
    25. }
    26. return mv;
    27. }
    28. }

    4、json的通统一异常处理

    GlobalExceptionResolver2
    1. package com.zking.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.RequestAttribute;
    5. import org.springframework.web.bind.annotation.RestControllerAdvice;
    6. import org.springframework.web.servlet.ModelAndView;
    7. import java.util.HashMap;
    8. import java.util.Map;
    9. /**
    10. * @author 白未
    11. * @site 3185579318
    12. * @company xxx公司
    13. * @create  2022-08-23 22:56
    14. *
    15. * 当出现异常统一向前端响应错误信息的json数据
    16. */
    17. @RestControllerAdvice
    18. public class GlobalExceptionResolver2 {
    19. @ExceptionHandler
    20. public Map handler(Exception e){
    21. Map map = new HashMap();
    22. if(e instanceof GlobalException){
    23. GlobalException exception =(GlobalException)e;
    24. map.put("ex",exception.getMessage());
    25. map.put("msg","全局异常 GlobalExceptionResolver,错误码520");
    26. }else if(e instanceof RuntimeException) {
    27. RuntimeException exception = (RuntimeException) e;
    28. map.put("ex", exception.getMessage());
    29. map.put("msg", "运行时异常 GlobalExceptionResolver,错误码666");
    30. }
    31. return map;
    32. }
    33. }

  • 相关阅读:
    Zookeeper【Curator客户端Java版】从0到1——万字学习笔记
    C++ 引用的数组和数组的引用
    Shell 脚本编程——变量和运算符
    Python Opencv实践 - 二维码和条形码识别
    代码随想录算法训练营第三天| 203.移除链表元素、707.设计链表 、206.反转链表(JS写法)
    E中国集装箱涂料行业竞争态势及投资盈利预测报告2022-2028年
    切线空间以及TBN矩阵
    .net 6 使用 NEST 查询,时间字段传值踩坑
    断言与参数化
    再生龙clonezilla还原windows、linux操作系统(包含银河麒麟、ubuntu、centos等)
  • 原文地址:https://blog.csdn.net/yzq102873/article/details/126469151