SpringMVC之JSON数据返回及异常处理机制

目录

一.JSON数据的返回

二.异常处理机制

  2.1 异常处理方式一

2.2 异常处理方式二

2.3 异常处理方式三


一.JSON数据的返回

        JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于Web应用程序和服务之间的数据传输。通过使用JSON,数据可以以一种结构化的方式进行组织和存储,并可以方便地在不同的编程语言和平台之间进行解析和使用。

        1.1 要想使用JSON,首先老规矩先导入pom.xml依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.3</version>
</dependency> 

            1.2    接着就是spring-mvc.xml文件

<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">
    <!--处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
    <property name="supportedMediaTypes">
        <list>
            <value>text/html;charset=UTF-8</value>
            <value>text/json;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

    1.3.@ResponseBody注解

        我们使用json技术转换时,要先来了解这个注解:@ResponseBody注解的作用是将Controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。注意:在使用此注解之后不会再走视图解析器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。

        1.4 基础入门

           接下来,分别写几个方法,来返回不同的返回值分别是返回一个对象,一个数组,返回对象数组,返回JSON字符串.

        在这些方法上面都用到了@ResponseBody注解,如果这整个类里面的方法都是JSON格式的话就可以不需要在每一个方法上面写注解,而是可以在类上面打一个注解就好,

package com.yinzi.web;

/**
 * @author yinzi
 * @create 2023-09-13 14:06
 */

import com.yinzi.Biz.StrutsBiz;
import com.yinzi.model.Struts;
import com.yinzi.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/*@ResponseBody
@Controller  这两个可以用下面这个代替*/
@RestController
@RequestMapping("/struts/json")
public class JsonController {
    @Autowired
    private StrutsBiz StrutsBiz;

    /**
     * 返回List<T>
     */
  /*  @ResponseBody*/
    @RequestMapping("/list")
    public List<Struts> list(HttpServletRequest req, Struts struts){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Struts> lst = this.StrutsBiz.selectList(struts,pageBean);
        return lst;
    }

    /**
     * 返回T
     * @param req
     * @return
     */
  /*  @ResponseBody*/
    @RequestMapping("/load")
    public Struts load(HttpServletRequest req, Struts struts){
        if(struts.getCid() != null){
            List<Struts> lst = this.StrutsBiz.selectList(struts, null);
            return lst.get(0);
        }
        return null;
    }


    /**
     * 返回List<Map>
     * @param req
     * @return
     */
   /* @ResponseBody*/
    @RequestMapping("/mapList")
    public List<Map> mapList(HttpServletRequest req, Struts clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Map> lst = this.StrutsBiz.mapList(clazz, pageBean);
        return lst;
    }

    /**
     * 返回Map
     * @param req
     * @return
     */
   /* @ResponseBody*/
    @RequestMapping("/mapLoad")
    public Map mapLoad(HttpServletRequest req, Struts struts){
        if(struts.getCid() != null){
            List<Map> lst = this.StrutsBiz.mapList(struts, null);
            return lst.get(0);
        }
        return null;
    }


   /* @ResponseBody*/
    @RequestMapping("/all")
    public Map all(HttpServletRequest req, Struts struts){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Struts> lst = this.StrutsBiz.selectList(struts, pageBean);
        Map map = new HashMap();
        map.put("lst",lst);
        map.put("pageBean",pageBean);
        return map;
    }

   /* @ResponseBody*/
    @RequestMapping("/jsonStr")
    public String jsonStr(HttpServletRequest req, Struts struts){
        return "clzEdit";//返回字符串
    }


}

        1.5 结果测试

        大家可以看到输入框中的路径的变化,调用了不同的方法

        1.6 @JsonIgnore注解使用

        如果我们要隐藏属性不被看到的话就可以把这个注解放在属性的上面

可以和上方动图比较,有了这个注解,页面上就不会显示  pic  这个属性了 

二.异常处理机制

        全局异常处理指的是在应用程序的运行过程中,捕获和处理未被明确捕获的异常。它的目的是在发生异常时,能够提供一个统一的处理方式,以保证应用程序的稳定性和可靠性。

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

        2.1 异常处理方式一

        改变spring-mvc配置文件

<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <!-- 定义默认的异常处理页面 -->
    <property name="defaultErrorView" value="error"/>
    <!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception --> 
    <property name="exceptionAttribute" value="ex"/>
    <!-- 定义需要特殊处理的异常,这是重要点 --> 
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.RuntimeException">error</prop>
        </props>
    	<!-- 还可以定义其他的自定义异常 -->
    </property>
</bean> 

         error.jsp界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
错误❌信息页面
${ex}
</body>
</html>

接着创建一个错误,以演示 

结果:

 

2.2 异常处理方式二

1.通过instanceof判断异常类型
2.通过设置mv.setView(new MappingJackson2JsonView())方式返回JSON数据

建立一个全局异常的类

package com.yinzi.Component;

import com.yinzi.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;

/**
 * @author yinzi
 * @create 2023-09-13 16:28
 */
@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;
    }
}

        在方法中调用

        结果:

2.3 异常处理方式三

建立异常类

package com.yinzi.Component;

import com.yinzi.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;
    }
}

结果:

返回的是json数据,而不是页面,如果打开上面的就是返回页面

        今天的分享就到这啦!!

  • 12
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值