• JSON和全局异常处理


    目录

    一、SpringMVC对JSON的支持

     1、pom依赖

    2、Springmvc.xml配置

    3、后台代码

    ①ClazzBiz

    ②ClazzBizImpl

    ③ClazzMapper.java

    ④ClazzMapper.xml

    ⑤JsonController

    4、前台测试

    ①index.jsp

    运行效果:

    二、SpringMVC 的全局异常处理

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

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

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

    ①GlobalException

    ②GlobalExceptionHandler

    ③controller层

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

     5、全局异常处理JSON返回


    一、SpringMVC对JSON的支持

     1、pom依赖

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

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

    3、后台代码

    ①ClazzBiz

    1. package com.liaoxin.ssm.biz;
    2. import com.liaoxin.ssm.model.Clazz;
    3. import com.liaoxin.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.liaoxin.ssm.biz.impl;
    2. import com.liaoxin.ssm.biz.ClazzBiz;
    3. import com.liaoxin.ssm.mapper.ClazzMapper;
    4. import com.liaoxin.ssm.model.Clazz;
    5. import com.liaoxin.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. @Service
    11. public class ClazzBizImpl implements ClazzBiz {
    12. @Autowired
    13. private ClazzMapper clazzMapper;
    14. @Override
    15. public int deleteByPrimaryKey(Integer cid) {
    16. return clazzMapper.deleteByPrimaryKey(cid);
    17. }
    18. @Override
    19. public int insert(Clazz record) {
    20. return clazzMapper.insert(record);
    21. }
    22. @Override
    23. public int insertSelective(Clazz record) {
    24. return clazzMapper.insertSelective(record);
    25. }
    26. @Override
    27. public Clazz selectByPrimaryKey(Integer cid) {
    28. return clazzMapper.selectByPrimaryKey(cid);
    29. }
    30. @Override
    31. public int updateByPrimaryKeySelective(Clazz record) {
    32. return clazzMapper.updateByPrimaryKeySelective(record);
    33. }
    34. @Override
    35. public int updateByPrimaryKey(Clazz record) {
    36. return clazzMapper.updateByPrimaryKey(record);
    37. }
    38. @Override
    39. public List listPager(Clazz clazz, PageBean pageBean) {
    40. return clazzMapper.listPager(clazz);
    41. }
    42. @Override
    43. public List listMapPager(Clazz clazz, PageBean pageBean) {
    44. return clazzMapper.listMapPager(clazz);
    45. }
    46. }

    ③ClazzMapper.java

    1. package com.liaoxin.ssm.mapper;
    2. import com.liaoxin.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.liaoxin.ssm.mapper.ClazzMapper" >
    4. <resultMap id="BaseResultMap" type="com.liaoxin.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.liaoxin.ssm.model.Clazz" parameterType="com.liaoxin.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 cid = #{cid}
    31. if>
    32. where>
    33. select>
    34. <select id="listMapPager" resultType="java.util.Map" parameterType="com.liaoxin.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.liaoxin.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.liaoxin.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.liaoxin.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.liaoxin.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.liaoxin.ssm.web;
    2. import com.liaoxin.ssm.biz.ClazzBiz;
    3. import com.liaoxin.ssm.model.Clazz;
    4. import com.liaoxin.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 liaoxin
    15. * @create 2022-08-22 16:27
    16. */
    17. @Controller
    18. @RequestMapping("/clz/json")
    19. public class JsonController {
    20. @Autowired
    21. private ClazzBiz clazzBiz;
    22. @ResponseBody
    23. @RequestMapping("/clzEdit")
    24. public String clzEdit(){
    25. System.out.println("JsonController.list");
    26. return "clzEdit";
    27. }
    28. // list
    29. @ResponseBody
    30. @RequestMapping("/list")
    31. public List list(HttpServletRequest request,Clazz clazz){
    32. // System.out.println("JsonController.list");
    33. PageBean pageBean=new PageBean();
    34. pageBean.setRequest(request);
    35. // [{},{}]
    36. return this.clazzBiz.listPager(clazz,pageBean);
    37. }
    38. // list
    39. @ResponseBody
    40. @RequestMapping("/listMap")
    41. public List listMap(HttpServletRequest request, Clazz clazz){
    42. // System.out.println("JsonController.list");
    43. PageBean pageBean=new PageBean();
    44. pageBean.setRequest(request);
    45. // [{},{}]
    46. return
    47. this.clazzBiz.listMapPager(clazz,pageBean);
    48. }
    49. // Map
    50. @ResponseBody
    51. @RequestMapping("/map")
    52. public Map map(HttpServletRequest request, Clazz clazz){
    53. // System.out.println("JsonController.list");
    54. PageBean pageBean=new PageBean();
    55. pageBean.setRequest(request);
    56. // {}
    57. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    58. }
    59. // T
    60. @ResponseBody
    61. @RequestMapping("/load")
    62. public Clazz load(HttpServletRequest request, Clazz clazz){
    63. // http://localhost:8080/clz/json/load?cid=2
    64. // System.out.println("JsonController.list");
    65. PageBean pageBean=new PageBean();
    66. pageBean.setRequest(request);
    67. // {}
    68. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    69. }
    70. // {
    71. // msg:"",
    72. // code:200,
    73. // data:[],
    74. // pageBean:{}
    75. // }
    76. @ResponseBody
    77. @RequestMapping("/hunhe")
    78. public Map hunhe(HttpServletRequest request, Clazz clazz){
    79. // http://localhost:8080/clz/json/load?cid=2
    80. PageBean pageBean=new PageBean();
    81. pageBean.setRequest(request);
    82. List lst = this.clazzBiz.listPager(clazz, pageBean);
    83. Map map = new HashMap();
    84. map.put("data",lst);
    85. map.put("pagebean",pageBean);
    86. return map;
    87. // return this.clazzBiz.listPager(clazz,pageBean).get(0);
    88. }
    89. }

    4、前台测试

    ①index.jsp

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

    运行效果:

     List

    List

     

     返回T对象

    返回map对象

     返回混合对象

    二、SpringMVC 的全局异常处理

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

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

    2、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/22
    5. Time: 17:17
    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>Titletitle>
    12. head>
    13. <body>
    14. ${ex}
    15. body>
    16. html>

    返回List对象

     返回List对象

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

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

    ①GlobalException

    1. package com.liaoxin.ssm.exception;
    2. /**
    3. * @author liaoxin
    4. * @create 2022-08-22 17:20
    5. */
    6. public class GlobalException extends RuntimeException{
    7. public GlobalException() {
    8. super();
    9. }
    10. public GlobalException(String message) {
    11. super(message);
    12. }
    13. public GlobalException(String message, Throwable cause) {
    14. super(message, cause);
    15. }
    16. public GlobalException(Throwable cause) {
    17. super(cause);
    18. }
    19. protected GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    20. super(message, cause, enableSuppression, writableStackTrace);
    21. }
    22. }

    ②GlobalExceptionHandler

    1. package com.liaoxin.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 liaoxin
    9. * @create 2022-08-22 18:11
    10. */
    11. @Component
    12. public class GlobalExceptionHandler implements HandlerExceptionResolver {
    13. @Override
    14. public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, 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);
    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. }

    ③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 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. }

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

    GlobalExceptionResolver:

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

     5、全局异常处理JSON返回

    GlobalExceptionJsonResolver:

    1. package com.liaoxin.ssm.exception;
    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 liaoxin
    8. * @create 2022-08-22 18:50
    9. */
    10. @RestControllerAdvice
    11. public class GlobalExceptionJsonResolver {
    12. @ExceptionHandler
    13. public Map handler(Exception e){
    14. Map map = new HashMap();
    15. if(e instanceof GlobalException){
    16. GlobalException globalException = (GlobalException) e;
    17. map.put("ex",globalException.getMessage());
    18. map.put("msg","全局异常");
    19. }else if(e instanceof RuntimeException){
    20. RuntimeException runtimeException = (RuntimeException) e;
    21. map.put("ex",runtimeException.getMessage());
    22. map.put("msg","运行时异常");
    23. }
    24. return map;
    25. }
    26. }

  • 相关阅读:
    冥想第五百九十四天
    2023年中国稻谷加工机械分类、市场规模及发展前景分析[图]
    Windows访问centOS的Tomcat
    原来掌握这些就已经是高级测试工程师!后悔没早点发现!
    【微服务】微服务常见概念
    springboot11:原生组件注入
    LabVIEW中将前面板置于所有桌面窗口的前面
    SpringCloud之NamedContextFactory
    文档翻译-文档翻译软件
    基于51单片机的停车场车位管理系统仿真设计
  • 原文地址:https://blog.csdn.net/qq_44247968/article/details/126495268