• SpringMVC对JSON的支持& SpringMVC的全局异常处理


    目录

    一、SpringMVC对JSON的支持

    1、JOSN的各种场景

    2、pom依赖

    3、Springmvc.xml配置

    4、后台代码

    4.1ClazzBiz

    4.2 ClazzBizImpl

    4.3 ClazzMapper

    4.4 ClazzMapper.xml

    4.5 JsonController

    5、前台测试

      index.jsp

    二、SpringMVC 的全局异常处理

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

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

    2.1GlobalException

    2.2 GlobalException

    2.3 controller层

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

    4、全局异常处理JSON返回


    一、SpringMVC对JSON的支持

    1、JOSN的各种场景

    1.1返回List
    1.2返回List
    1.3返回T
    1.4返回Map
    1.5返回混合

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

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

    4、后台代码

    4.1ClazzBiz

    1. package com.zsx.ssm.biz;
    2. import com.zsx.ssm.model.Clazz;
    3. import com.zsx.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 record, PageBean pageBean);
    14. List listMapPager(Clazz record, PageBean pageBean);
    15. }

    4.2 ClazzBizImpl

    1. package com.zsx.ssm.biz.impl;
    2. import com.zsx.ssm.biz.ClazzBiz;
    3. import com.zsx.ssm.mapper.ClazzMapper;
    4. import com.zsx.ssm.model.Clazz;
    5. import com.zsx.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 zsx
    12. * @site 155954····
    13. * @company 交换余生
    14. * @create 2022--08--17 18:23
    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 record, PageBean pageBean) {
    38. return clazzMapper.listPager(record);
    39. }
    40. @Override
    41. public List listMapPager(Clazz record, PageBean pageBean) {
    42. if (true)
    43. throw new RuntimeException("查询班级信息 异常出现在 ClazzBizImpl.list...");
    44. return clazzMapper.listMapPager(record,pageBean);
    45. }
    46. @Override
    47. public int updateByPrimaryKeySelective(Clazz record) {
    48. return clazzMapper.updateByPrimaryKeySelective(record);
    49. }
    50. @Override
    51. public int updateByPrimaryKey(Clazz record) {
    52. return clazzMapper.updateByPrimaryKey(record);
    53. }
    54. }

    4.3 ClazzMapper

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

    4.4 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.zsx.ssm.mapper.ClazzMapper" >
    4. <resultMap id="BaseResultMap" type="com.zsx.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. <insert id="insert" parameterType="com.zsx.ssm.model.Clazz" >
    26. insert into t_struts_class (cid, cname, cteacher,
    27. pic)
    28. values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
    29. #{pic,jdbcType=VARCHAR})
    30. insert>
    31. <insert id="insertSelective" parameterType="com.zsx.ssm.model.Clazz" >
    32. insert into t_struts_class
    33. <trim prefix="(" suffix=")" suffixOverrides="," >
    34. <if test="cid != null" >
    35. cid,
    36. if>
    37. <if test="cname != null" >
    38. cname,
    39. if>
    40. <if test="cteacher != null" >
    41. cteacher,
    42. if>
    43. <if test="pic != null" >
    44. pic,
    45. if>
    46. trim>
    47. <trim prefix="values (" suffix=")" suffixOverrides="," >
    48. <if test="cid != null" >
    49. #{cid,jdbcType=INTEGER},
    50. if>
    51. <if test="cname != null" >
    52. #{cname,jdbcType=VARCHAR},
    53. if>
    54. <if test="cteacher != null" >
    55. #{cteacher,jdbcType=VARCHAR},
    56. if>
    57. <if test="pic != null" >
    58. #{pic,jdbcType=VARCHAR},
    59. if>
    60. trim>
    61. insert>
    62. <update id="updateByPrimaryKeySelective" parameterType="com.zsx.ssm.model.Clazz" >
    63. update t_struts_class
    64. <set >
    65. <if test="cname != null" >
    66. cname = #{cname,jdbcType=VARCHAR},
    67. if>
    68. <if test="cteacher != null" >
    69. cteacher = #{cteacher,jdbcType=VARCHAR},
    70. if>
    71. <if test="pic != null" >
    72. pic = #{pic,jdbcType=VARCHAR},
    73. if>
    74. set>
    75. where cid = #{cid,jdbcType=INTEGER}
    76. update>
    77. <update id="updateByPrimaryKey" parameterType="com.zsx.ssm.model.Clazz" >
    78. update t_struts_class
    79. set cname = #{cname,jdbcType=VARCHAR},
    80. cteacher = #{cteacher,jdbcType=VARCHAR},
    81. pic = #{pic,jdbcType=VARCHAR}
    82. where cid = #{cid,jdbcType=INTEGER}
    83. update>
    84. <select id="listPager" resultType="com.zsx.ssm.model.Clazz" parameterType="com.zsx.ssm.model.Clazz" >
    85. select
    86. <include refid="Base_Column_List" />
    87. from t_struts_class
    88. <where>
    89. <if test="cname != null and cname != ''">
    90. and cname like CONCAT('%',#{cname},'%')
    91. if>
    92. <if test="cid !=null and cid != ''">
    93. and cid = #{cid}
    94. if>
    95. where>
    96. select>
    97. <select id="listMapPager" resultType="java.util.Map" parameterType="com.zsx.ssm.model.Clazz">
    98. select
    99. <include refid="Base_Column_List" />
    100. from t_struts_class
    101. <where>
    102. <if test="cname != null and cname != ''">
    103. and cname like CONCAT('%',#{cname},'%')
    104. if>
    105. <if test="cid !=null and cid != ''">
    106. and cid = #{cid}
    107. if>
    108. where>
    109. select>
    110. mapper>

    4.5 JsonController

    1. package com.zsx.ssm.controller;
    2. import com.zsx.ssm.biz.ClazzBiz;
    3. import com.zsx.ssm.model.Clazz;
    4. import com.zsx.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 org.springframework.web.bind.annotation.RestController;
    10. import javax.servlet.http.HttpServletRequest;
    11. import java.util.HashMap;
    12. import java.util.List;
    13. import java.util.Map;
    14. /**
    15. * @author zsx
    16. * @site 155954····
    17. * @company 交换余生
    18. * @create 2022--08--22 16:28
    19. * 注:@RestController = @ResponseBody + @Controller
    20. */
    21. @ResponseBody
    22. //@Controller
    23. //@RestController
    24. @RequestMapping("/json")
    25. public class JsonController {
    26. @Autowired
    27. private ClazzBiz clazzBiz;
    28. @RequestMapping("/clzEdit")
    29. public String clzEdit(){
    30. System.out.println("JsonController.list");
    31. return "clzEdit";
    32. }
    33. @RequestMapping("/list")
    34. public List list(HttpServletRequest request ,Clazz clazz){
    35. PageBean pageBean=new PageBean();
    36. pageBean.setRequest(request);
    37. // if (true)
    38. // throw new RuntimeException("查询班级信息 异常出现在 JsonController.list...");
    39. return this.clazzBiz.listPager(clazz,pageBean);
    40. }
    41. @RequestMapping("/listMap")
    42. public List listMap(HttpServletRequest request , Clazz clazz){
    43. PageBean pageBean=new PageBean();
    44. pageBean.setRequest(request);
    45. return this.clazzBiz.listMapPager(clazz,pageBean);
    46. }
    47. @RequestMapping("/map")
    48. public Map map(HttpServletRequest request , Clazz clazz){
    49. PageBean pageBean=new PageBean();
    50. pageBean.setRequest(request);
    51. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    52. }
    53. @RequestMapping("/load")
    54. public Clazz load(HttpServletRequest request , Clazz clazz){
    55. PageBean pageBean=new PageBean();
    56. pageBean.setRequest(request);
    57. // if(true)
    58. // throw new RuntimeException("系统繁忙,请参考007");
    59. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    60. }
    61. @RequestMapping("/hunhe")
    62. public Map hunhe(HttpServletRequest request , Clazz clazz){
    63. PageBean pageBean=new PageBean();
    64. pageBean.setRequest(request);
    65. List lst = this.clazzBiz.listPager(clazz, pageBean);
    66. Map map=new HashMap();
    67. map.put("lst",lst);
    68. map.put("pageBean",pageBean);
    69. return map;
    70. }
    71. }

    5、前台测试

      index.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Administrator
    4. Date: 2022/8/22
    5. Time: 16:48
    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>测试jsontitle>
    12. head>
    13. <body>
    14. <a href="${pageContext.request.contextPath}/json/list">返回List<T>a><hr>
    15. <a href="${pageContext.request.contextPath}/json/listMap">返回List<Map>a><hr>
    16. <a href="${pageContext.request.contextPath}/json/load?cid=1">返回Ta><hr>
    17. <a href="${pageContext.request.contextPath}/json/map?cid=1">返回Mapa><hr>
    18. <a href="${pageContext.request.contextPath}/json/hunhe">返回混合a>
    19. body>
    20. html>

    运行效果:

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

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

    2.1GlobalException

    1. package com.zsx.ssm.exception;
    2. /**
    3. * @author zsx
    4. * @site 155954····
    5. * @company 交换余生
    6. * @create 2022--08--22 18:33
    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 GlobalException

    1. package com.zsx.ssm.exception;
    2. /**
    3. * @author zsx
    4. * @site 155954····
    5. * @company 交换余生
    6. * @create 2022--08--22 18:33
    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.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 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. }

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

    GlobalExceptionResolver

    1. package com.zsx.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 org.springframework.web.servlet.HandlerExceptionResolver;
    6. import org.springframework.web.servlet.ModelAndView;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. /**
    10. * @author zsx
    11. * @site 155954····
    12. * @company 交换余生
    13. *
    14. *
    15. * @create 2022--08--22 18:35
    16. */
    17. @ControllerAdvice
    18. public class GlobalExceptionResovler{
    19. @ExceptionHandler//异常处理器
    20. public ModelAndView handler(Exception e) {
    21. ModelAndView mv=new ModelAndView();
    22. mv.setViewName("error");
    23. if(e instanceof GlobalException){
    24. GlobalException exception= (GlobalException) e;
    25. mv.addObject("ex",exception.getMessage());
    26. mv.addObject("msg","全局异常,GlobalExceptionResovler错误码501");
    27. }else if(e instanceof RuntimeException){
    28. RuntimeException exception= (RuntimeException) e;
    29. mv.addObject("ex",exception.getMessage());
    30. mv.addObject("msg","运行异常,GlobalExceptionResovler错误码601");
    31. }
    32. return mv;
    33. }
    34. }

    4、全局异常处理JSON返回

    GlobalExceptionJsonResolver

    1. package com.zsx.ssm.exception;
    2. import org.springframework.stereotype.Component;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.servlet.HandlerExceptionResolver;
    5. import org.springframework.web.servlet.ModelAndView;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. /**
    9. * @author zsx
    10. * @site 155954····
    11. * @company 交换余生
    12. *
    13. *
    14. * @create 2022--08--22 18:35
    15. * 处理全局异常的解析器
    16. */
    17. //@Component
    18. public class GlobalHandlerExceptionResovler implements HandlerExceptionResolver {
    19. @Override
    20. public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    21. ModelAndView mv=new ModelAndView();
    22. mv.setViewName("error");
    23. if(e instanceof GlobalException){
    24. GlobalException exception= (GlobalException) e;
    25. mv.addObject("ex",exception.getMessage());
    26. mv.addObject("msg","全局异常,错误码501");
    27. }else if(e instanceof RuntimeException){
    28. RuntimeException exception= (RuntimeException) e;
    29. mv.addObject("ex",exception.getMessage());
    30. mv.addObject("msg","运行异常,错误码601");
    31. }
    32. return mv;
    33. }
    34. }

     效果图:

  • 相关阅读:
    【领域驱动设计】架构和 DDD Kata:在线汽车经销商
    【全志T113-S3_100ask】15-2 linux系统gpio模拟spi驱动屏幕——ILI9341
    Java ZooKeeper-RocketMQ 面试题
    椭圆曲线算法
    51【Aseprite 作图】酒坛——拆解
    如何阅读论文、文献的搜索与免费下载的一件套总结
    如何理解对数差异、比对数几率
    HashMap是怎么解决哈希冲突的?
    数据结构和算法简介
    给你一份精心设计的消息中间件高扩展架构,赶紧写进简历吧!
  • 原文地址:https://blog.csdn.net/weixin_61523879/article/details/126492642