• “深入理解SpringMVC的JSON数据返回和异常处理机制“



    在这里插入图片描述

    引言

    在现代Web开发中,SpringMVC是一个广泛使用的框架,它提供了丰富的功能和灵活的配置选项。本文将深入探讨两个重要的主题:SpringMVC中的JSON数据返回和异常处理机制。我们将逐步介绍相关的配置和使用方法,并通过案例和综合实例来加深理解。

    1. SpringMVC之JSON数据返回

    1.1 导入依赖

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

    1.2 配置弹簧-MVC.xml

    为了使SpringMVC能够正确处理JSON数据返回,我们需要在配置文件中进行相应的配置。以便正确处理JSON数据返回的请求。

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
            	<ref bean="mappingJackson2HttpMessageConverter"/>
            list>
        property>
    bean>
    <bean id="mappingJackson2HttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
                <value>text/json;charset=UTF-8value>
                <value>application/json;charset=UTF-8value>
            list>
        property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    1.3 @ResponseBody注解使用

    @ResponseBody注解的作用是将Controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。

    注意:在使用此注解之后不会再走视图解析器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。

     <select id="selBySnamePager" resultType="com.yuan.model.Student" parameterType="com.yuan.model.Student" >
        select
        <include refid="Base_Column_List" />
        from t_mysql_student
        <where>
          <if test="sname!=null">
            and sname like concat('%',#{sname},'%')
          if>
        where>
    
      select>
    
      <select id="mapListPager" resultType="java.util.Map" parameterType="com.yuan.model.Student" >
        select
        <include refid="Base_Column_List" />
        from t_mysql_student
        <where>
          <if test="sname != null">
            and sname like concat('%',#{sname},'%')
          if>
        where>
      select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    
        /**
         * 返回List
         * @param req
         * @param student
         * @return
         */
        @ResponseBody
        @RequestMapping("/list")
        public List<Student> list(HttpServletRequest req, Student student){
            PageBean pageBean = new PageBean();
            pageBean.setRequest(req);
            List<Student> lst = this.studentBiz.selBySnamePager(student, pageBean);
            return lst;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

      /**
         * 返回T
         * @param req
         * @param Student
         * @return
         */
        @ResponseBody
        @RequestMapping("/load")
        public Student load(HttpServletRequest req, Student Student){
            if(Student.getSname() != null){
                List<Student> lst = this.studentBiz.selBySnamePager(Student, null);
                return lst.get(0);
            }
            return null;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

      /**
         * 返回List
         * @param req
         * @param Student
         * @return
         */
        @ResponseBody
        @RequestMapping("/mapList")
        public List<Map> mapList(HttpServletRequest req, Student Student){
            PageBean pageBean = new PageBean();
            pageBean.setRequest(req);
            List<Map> lst = this.studentBiz.mapListPager(Student, pageBean);
            return lst;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

     /**
         * 返回Map
         * @param req
         * @param Student
         * @return
         */
        @ResponseBody
        @RequestMapping("/mapLoad")
        public Map mapLoad(HttpServletRequest req, Student Student){
            if(Student.getSname() != null){
                List<Map> lst = this.studentBiz.mapListPager(Student, null);
                return lst.get(0);
            }
            return null;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

     @ResponseBody
        @RequestMapping("/all")
        public Map all(HttpServletRequest req, Student Student){
            PageBean pageBean = new PageBean();
            pageBean.setRequest(req);
            List<Student> lst = this.studentBiz.selBySnamePager(Student, pageBean);
            Map map = new HashMap();
            map.put("lst",lst);
            map.put("pageBean",pageBean);
            return map;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    @ResponseBody
        @RequestMapping("/jsonStr")
        public String jsonStr(HttpServletRequest req, Student Student){
            return "clzEdit";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    • @JsonIgnore 隐藏json数据中的某个属性
    
    @ToString
    public class Student {
        @JsonIgnore
        @NotBlank(message = "编号不能为空")
        private String sid;
        @NotBlank(message = "名字不能为空")
        private String sname;
        @NotBlank(message = "年龄不能为空")
        private String sage;
        @NotBlank(message = "性别不能为空")
        private String ssex;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在这里插入图片描述

    1.4.Jackson

    • 1.4.1.介绍

    ​ Jackson是一个简单基于Java应用库,Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。Jackson所依赖的jar包较少,简单易用并且性能也要相对高些,并且Jackson社区相对比较活跃,更新速度也比较快。

    特点

    • 容易使用,提供了高层次外观,简化常用的用例。
    • 无需创建映射,API提供了默认的映射大部分对象序列化。
    • 性能高,快速,低内存占用
    • 创建干净的json
    • 不依赖其他库
    • 代码开源

    1.4.2.常用注解

    注解说明
    @JsonIgnore作用在字段或方法上,用来完全忽略被注解的字段和方法对应的属性
    @JsonProperty作用在字段或方法上,用来对属性的序列化/反序列化,可以用来避免遗漏属性,同时提供对属性名称重命名
    @JsonIgnoreProperties作用在类上,用来说明有些属性在序列化/反序列化时需要忽略掉
    @JsonUnwrapped作用在属性字段或方法上,用来将子JSON对象的属性添加到封闭的JSON对象
    @JsonFormat指定序列化日期/时间值时的格式

    2. 异常处理机制

    2.1 为什么要全局异常处理

    异常处理是一个重要的开发任务,它可以帮助我们更好地处理程序中的错误和异常情况。本节将介绍为什么我们需要全局异常处理机制,并讨论其重要性和优势。

    2.2 异常处理思路

    系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
    在这里插入图片描述

    2.3 SpringMVC异常分类

    • 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
    • 实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;
    • 使用@ControllerAdvice + @ExceptionHandler

    2.4 综合案例

    通过一个综合案例,我们将深入了解如何在SpringMVC中处理异常情况。本节将介绍一个实际的案例,并演示如何使用全局异常处理机制来处理异常。

    • 异常处理方式一

    SpringMVC中自带了一个异常处理器叫SimpleMappingExceptionResolver,该处理器实现了HandlerExceptionResolver 接口,全局异常处理器都需要实现该接口。

    
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        
        <property name="defaultErrorView" value="error"/>
         
        <property name="exceptionAttribute" value="ex"/>
         
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.RuntimeException">errorprop>
            props>
        	
        property>
    bean> 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • error.jsp
    <%--
      Created by IntelliJ IDEA.
      User: yuanh
      Date: 2023/9/13
      Time: 16:07
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Titletitle>
    head>
    <body>
    异常
    ${ex}
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 异常代码

    在这里插入图片描述

    • 运行异常效果
      在这里插入图片描述

    • 异常处理方式二

    GlobalException

    package com.yuan.exception;
    
    public class GlobalException extends RuntimeException {
        public GlobalException() {
        }
    
        public GlobalException(String message) {
            super(message);
        }
    
        public GlobalException(String message, Throwable cause) {
            super(message, cause);
        }
    
        public GlobalException(Throwable cause) {
            super(cause);
        }
    
        public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    GlobalExceptionHandler

    package com.yuan.Component;
    
    import com.yuan.exception.GlobalException;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @Component
    public class GlobalExceptionHandler implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                             HttpServletResponse httpServletResponse,
                                             Object o, Exception e) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("error");
            if (e instanceof GlobalException){
                GlobalException globalException = (GlobalException) e;
                mv.addObject("ex",globalException.getMessage());
                mv.addObject("msg","全局异常....");
            }else if (e instanceof RuntimeException){
                RuntimeException runtimeException = (RuntimeException) e;
                mv.addObject("ex",runtimeException.getMessage());
                mv.addObject("msg","运行时异常....");
            }else {
                mv.addObject("ex",e.getMessage());
                mv.addObject("msg","其他异常....");
    
            }
            return mv;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    异常方法

        @ResponseBody
        @RequestMapping("/jsonStr")
        public String jsonStr(HttpServletRequest req, Student Student){
            if(true)
            throw  new GlobalException("异常123");
            return "clzEdit";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述
    在这里插入图片描述

    • 处理异常三@ControllerAdvice
    package com.yuan.Component;
    
    import com.yuan.exception.GlobalException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @ControllerAdvice
    public class GlobalExceptionResolver {
    
    //    跳转错误页面
    //    @ExceptionHandler
    //    public ModelAndView handler(Exception e){
    //        ModelAndView mv = new ModelAndView();
    //        mv.setViewName("error");
    //        if (e instanceof GlobalException){
    //            GlobalException globalException = (GlobalException) e;
    //            mv.addObject("ex",globalException.getMessage());
    //            mv.addObject("msg","全局异常....");
    //        }else if (e instanceof RuntimeException){
    //            RuntimeException runtimeException = (RuntimeException) e;
    //            mv.addObject("ex",runtimeException.getMessage());
    //            mv.addObject("msg","运行时异常....");
    //        }
    //        return mv;
    //    }
    
    // 返回错误json数据
        @ResponseBody
        @ExceptionHandler
        public Map handler(Exception e){
            Map map = new HashMap();
            if (e instanceof GlobalException){
                GlobalException globalException = (GlobalException) e;
                map.put("ex",globalException.getMessage());
                map.put("msg","全局异常....");
            }else if (e instanceof RuntimeException){
                RuntimeException runtimeException = (RuntimeException) e;
                map.put("ex",runtimeException.getMessage());
                map.put("msg","运行时异常....");
            }else {
                map.put("ex",e.getMessage());
                map.put("msg","其它异常....");
            }
            return map;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    在这里插入图片描述
    在这里插入图片描述

    总结

    本文深入探讨了SpringMVC中的JSON数据返回和异常处理机制。我们从配置和使用方法入手,逐步介绍了相关的知识点,并通过案例和综合实例加深了理解。希望本文能够帮助读者更好地理解和应用SpringMVC中的JSON数据返回和异常处理机制。

  • 相关阅读:
    基于SpringBoot的电影评论网站
    Verilog 过程赋值(阻塞赋值,非阻塞赋值,并行)
    GoWeb 的 MVC 入门实战案例,基于 Iris 框架实现(附案例全代码)
    记一次地市hw从供应商-目标站-百万信息泄露
    makefile 中命令包及eval的使用
    使用Nginx实现采集端和数据分析平台的数据加密传输
    深入探索 MongoDB:高级索引解析与优化策略
    给Git仓库添加.gitignore:清理、删除、排除被Git误添加的临时文件
    k8s-Pod调度
    色温曲线坐标轴的选取:G/R、G/B还是R/G、B/G ?
  • 原文地址:https://blog.csdn.net/2201_75869073/article/details/132852544