• JSON和全局异常处理


    目录

    1.SpringMVC对JSON的支持

    1.1 JOSN的各种场景

    1.2 pom依赖

    1.3 Springmvc.xml配置

    1.4.后台代码:

    1.5 前端代码:

    2.SpringMVC 的全局异常处理 

    2.1:SpringMVC自带的简单异常处理器

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

    代码展示:

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

    2.4全局异常处理JSON返回


    1.SpringMVC对JSON的支持

    1.1 JOSN的各种场景

    1.1.1返回List

    1.1.2返回List

    1.1.3返回T

    1.1.4返回Map

    1.1.5返回混合

    1.1.6返回JSON字符串

    1.2 pom依赖

     

          com.fasterxml.jackson.core

          jackson-databind

          2.9.3

        

        

          com.fasterxml.jackson.core

          jackson-core

          2.9.3

        

        

          com.fasterxml.jackson.core

          jackson-annotations

          2.9.3

        

    1.3 Springmvc.xml配置

            

                

                    

                

            

        

        

              class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

            

            

                

                    text/html;charset=UTF-8

                    text/json;charset=UTF-8

                    application/json;charset=UTF-8

                

            

        

    1.4.后台代码:

    clazzBiz:

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

    ClazzMapper.java:

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

    1.5 前端代码:

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

    效果展示:

     list:

    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>

    测试类:

    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对象:

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

    代码展示:

    GlobalException:

    1. package com.xbb.ssm.exception;
    2. /**
    3. * @author冰冰
    4. * @create  2022-08-23 20:33
    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.xbb.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. * @create 2022-08-23 20:50
    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. }

    GlobalExceptionHandler:

    1. package com.xbb.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. * @create 2022-08-23 21:29
    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. }

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

    1. package com.xbb.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. * @create 2022-08-23 21:50
    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. }

    2.4全局异常处理JSON返回

    1. package com.xbb.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 冰冰
    8. * @create 2022-08-23 21:55
    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. }

  • 相关阅读:
    解决git提交:Please enter a commit message to explain why this merge is necessary
    Maven基础简介+安装说明
    【Bio】基础生物学 - 基因 gene
    70行代码撸一个桌面自动翻译神器!
    Java常用的设计模式
    SQLite使用
    应对电网挑战!lonQ与橡树岭国家实验室利用量子技术改善关键基础设施
    【定义】矩阵初等变换和矩阵等价
    SPIR-V初窥
    【苹果相册推软件源码】iMessage提出了UDP(UserDatagramprotocol,用户数据新闻协议
  • 原文地址:https://blog.csdn.net/m0_68211831/article/details/126492281