SpringMVC 04(JSON和全局异常处理)

目录

一,SpringMVC对JSON的支持            

二,SpringMVC 的全局异常处理


一,SpringMVC对JSON的支持     

pom.xml依赖

 
      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
    

   Springmvc.xml配置


        
            
                
            
        
    
    
        
        
            
                text/html;charset=UTF-8
                text/json;charset=UTF-8
                application/json;charset=UTF-8
            
        
    

后台代码:

package com.ruojuan.ssm.web;

import com.ruojuan.ssm.Exception.GlobalException;
import com.ruojuan.ssm.biz.ClazzBiz;
import com.ruojuan.ssm.model.Clazz;
import com.ruojuan.ssm.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 javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-22 16:25
 */
@ResponseBody
@Controller
@RequestMapping("/clz/json")
public class JsonController {

    @Autowired
    private ClazzBiz clazzBiz;

    /**
     * 返回List
     * @param req
     * @param clazz
     * @return
     */
    @RequestMapping("/list")
    public List list(HttpServletRequest req, Clazz clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        if(true) {
            throw new RuntimeException("查询班级信息异常,异常存在于JsonController.list方法");
        }
        List lst = this.clazzBiz.listPager(clazz, pageBean);
        return lst;
    }

    /**
     * 返回T
     * @param req
     * @param clazz
     * @return
     */
    /*@RequestMapping("/load")
    public Clazz load(HttpServletRequest req, Clazz clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        if(true){
          throw new GlobalException("系统繁忙,请参考E007;");
        }
        return this.clazzBiz.listPager(clazz,pageBean).get(0);
    }*/
    @RequestMapping("/load")
    public Clazz load(HttpServletRequest req, Clazz clazz){
        if(clazz.getCid() != null){
            List lst = this.clazzBiz.listPager(clazz, null);
            if (true)
                throw new GlobalException("错误出现在 JsonController.load...");
            return lst.get(0);
        }
        return null;
    }


    /**
     * 返回List
     * @param req
     * @param clazz
     * @return
     */
    @RequestMapping("/mapList")
    public List mapList(HttpServletRequest req, Clazz clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List lst = this.clazzBiz.listMapPager(clazz, pageBean);
        return lst;
    }

    /**
     * 返回Map
     * @param req
     * @param clazz
     * @return
     */
    @RequestMapping("/mapLoad")
    public Map mapLoad(HttpServletRequest req, Clazz clazz){
        if(clazz.getCid() != null){
            List lst = this.clazzBiz.listMapPager(clazz, null);
            return lst.get(0);
        }
        return null;
    }


    @RequestMapping("/all")
    public Map all(HttpServletRequest req, Clazz clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List lst = this.clazzBiz.listPager(clazz, pageBean);
        Map map = new HashMap();
        map.put("lst",lst);
        map.put("pageBean",pageBean);
        return map;
    }

    @RequestMapping("/jsonStr")
    public String jsonStr(HttpServletRequest req, Clazz clazz){
        return "Edit";
    }


}

servic层 :

public List mapListPager(Clazz clazz,PageBean pageBean) {
        return clazzMapper.mapListPager(clazz);
    }

 Mapper.xml

测试:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/22
  Time: 16:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    测试json数据返回



返回list<T>对象
返回list<Map>对象
返回T对象
返回Map对象
返回混合对象

 效果:

SpringMVC 04(JSON和全局异常处理)_第1张图片

 

 SpringMVC 04(JSON和全局异常处理)_第2张图片

 

 

二,SpringMVC 的全局异常处理

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

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

        2.异常处理思路

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

        3.SpringMVC异常分类   

   1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;

   2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;

   3)使用@ControllerAdvice + @ExceptionHandler

JsonController :

     /**
     * 返回List
     * @param req
     * @param clazz
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public List list(HttpServletRequest req, Clazz clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        if(true) {
            throw new RuntimeException("查询班级信息异常,异常存在于JsonController.list方法");
        }
        List lst = this.clazzBiz.listPager(clazz, pageBean);
        return lst;
    }



   /**
     * 返回List
     * @param req
     * @param clazz
     * @return
     */
    @ResponseBody
    @RequestMapping("/mapList")
    public List mapList(HttpServletRequest req, Clazz clazz){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List lst = this.clazzBiz.listMapPager(clazz, pageBean);
        return lst;
    }

Bizimpl:

 @Override
    public List listMapPager(Clazz clazz, PageBean pageBean) {
        if(true) {
            throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.list方法");
        }
        return clazzMapper.listMapPager(clazz);
    }

效果: 

SpringMVC 04(JSON和全局异常处理)_第3张图片

 SpringMVC 04(JSON和全局异常处理)_第4张图片

SpringMVC 04(JSON和全局异常处理)_第5张图片

SpringMVC自带的简单异常处理器

        springmvc-servlet.xml


    
        
        
        
        
        
        
            
                error
            
            
        
    

error.jsp

${ex}

 

 SpringMVC 04(JSON和全局异常处理)_第6张图片

  4. 通过HandlerExceptionResovler接口实现全局异常

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

全局异常GlobalException.java:

        

package com.ruojuan.ssm.Exception;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-22 17:16
 */
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);
    }
}

异常处理器 GlobalHandlerExceptionResovler 

package com.ruojuan.ssm.Exception;

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 ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-22 17:52
 *
 * 处理全局异常的解析器
 */
@Component
public class GlobalHandlerExceptionResovler implements HandlerExceptionResolver {


    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o 目标对象
     * @param e
     * @return
     */
    @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","全局异常,错误码501....");
        }else if (e instanceof RuntimeException){
            RuntimeException runtimeException = (RuntimeException) e;
            mv.addObject("ex",runtimeException.getMessage());
            mv.addObject("msg","运行时异常,错误码601....");
        }
        return mv;
    }
}

测试代码Controller层的改变

 @ResponseBody
    @RequestMapping("/load")
    public Clazz load(HttpServletRequest req, Clazz clazz){
        if(clazz.getCid() != null){
            List lst = this.clazzBiz.listPager(clazz, null);
            if (true)
                throw new GlobalException("错误出现在 JsonController.load...");
            return lst.get(0);
        }
        return null;
    }

SpringMVC 04(JSON和全局异常处理)_第7张图片

SpringMVC 04(JSON和全局异常处理)_第8张图片

 

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

package com.ruojuan.ssm.Exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-22 18:10
 */
//@ControllerAdvice

public class GlobalExceptionResovler {

    @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返回

package com.ruojuan.ssm.Exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-22 18:11
 *
 * 当出现异常,统一向前端响应错误后出现的结果
 */
//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionJsonResolver {

    @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","全局异常 GlobalExceptionResolver,错误码501....");
        }else if (e instanceof RuntimeException){
            RuntimeException runtimeException = (RuntimeException) e;
            map.put("ex",runtimeException.getMessage());
            map.put("msg","运行时异常 GlobalExceptionResolver,错误码601....");
        }
        return map;
    }

}

SpringMVC 04(JSON和全局异常处理)_第9张图片

 

你可能感兴趣的:(springMVC,spring,json,json,spring,idea)