目录
2、通过HandlerExceptionResovler接口实现全局异常
3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
1.1返回List
1.2返回List
1.3返回T
1.4返回Map
1.5返回混合
- <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>
-
- <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>
-
- package com.zsx.ssm.biz;
-
- import com.zsx.ssm.model.Clazz;
- import com.zsx.ssm.util.PageBean;
-
- import java.util.List;
- import java.util.Map;
-
- public interface ClazzBiz {
- int deleteByPrimaryKey(Integer cid);
-
- int insert(Clazz record);
-
- int insertSelective(Clazz record);
-
- Clazz selectByPrimaryKey(Integer cid);
-
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
-
- List
listPager(Clazz record, PageBean pageBean); -
- List
- }
- package com.zsx.ssm.biz.impl;
-
- import com.zsx.ssm.biz.ClazzBiz;
- import com.zsx.ssm.mapper.ClazzMapper;
- import com.zsx.ssm.model.Clazz;
- import com.zsx.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author zsx
- * @site 155954····
- * @company 交换余生
- * @create 2022--08--17 18:23
- */
-
- @Service
- public class ClazzBizImpl implements ClazzBiz {
- @Autowired
- private ClazzMapper clazzMapper;
-
- @Override
- public int deleteByPrimaryKey(Integer cid) {
- return clazzMapper.deleteByPrimaryKey(cid);
- }
-
- @Override
- public int insert(Clazz record) {
- return clazzMapper.insert(record);
- }
-
- @Override
- public int insertSelective(Clazz record) {
- return clazzMapper.insertSelective(record);
- }
-
- @Override
- public Clazz selectByPrimaryKey(Integer cid) {
- return clazzMapper.selectByPrimaryKey(cid);
- }
-
- @Override
- public List
listPager(Clazz record, PageBean pageBean) { - return clazzMapper.listPager(record);
- }
-
- @Override
- public List
- if (true)
- throw new RuntimeException("查询班级信息 异常出现在 ClazzBizImpl.list...");
- return clazzMapper.listMapPager(record,pageBean);
- }
-
- @Override
- public int updateByPrimaryKeySelective(Clazz record) {
- return clazzMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(Clazz record) {
- return clazzMapper.updateByPrimaryKey(record);
- }
- }
- package com.zsx.ssm.mapper;
-
- import com.zsx.ssm.model.Clazz;
- import com.zsx.ssm.util.PageBean;
- import org.springframework.stereotype.Repository;
-
- import java.util.List;
- import java.util.Map;
-
- @Repository
- public interface ClazzMapper {
- int deleteByPrimaryKey(Integer cid);
-
- int insert(Clazz record);
-
- int insertSelective(Clazz record);
-
- Clazz selectByPrimaryKey(Integer cid);
-
- List
listPager(Clazz record); -
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
-
- List
- }
- "1.0" encoding="UTF-8" ?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.zsx.ssm.mapper.ClazzMapper" >
- <resultMap id="BaseResultMap" type="com.zsx.ssm.model.Clazz" >
- <constructor >
- <idArg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
- <arg column="cname" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="cteacher" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="pic" jdbcType="VARCHAR" javaType="java.lang.String" />
- constructor>
- resultMap>
- <sql id="Base_Column_List" >
- cid, cname, cteacher, pic
- sql>
- <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
- select
- <include refid="Base_Column_List" />
- from t_struts_class
- where cid = #{cid,jdbcType=INTEGER}
- select>
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
- delete from t_struts_class
- where cid = #{cid,jdbcType=INTEGER}
- delete>
- <insert id="insert" parameterType="com.zsx.ssm.model.Clazz" >
- insert into t_struts_class (cid, cname, cteacher,
- pic)
- values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
- #{pic,jdbcType=VARCHAR})
- insert>
- <insert id="insertSelective" parameterType="com.zsx.ssm.model.Clazz" >
- insert into t_struts_class
- <trim prefix="(" suffix=")" suffixOverrides="," >
- <if test="cid != null" >
- cid,
- if>
- <if test="cname != null" >
- cname,
- if>
- <if test="cteacher != null" >
- cteacher,
- if>
- <if test="pic != null" >
- pic,
- if>
- trim>
- <trim prefix="values (" suffix=")" suffixOverrides="," >
- <if test="cid != null" >
- #{cid,jdbcType=INTEGER},
- if>
- <if test="cname != null" >
- #{cname,jdbcType=VARCHAR},
- if>
- <if test="cteacher != null" >
- #{cteacher,jdbcType=VARCHAR},
- if>
- <if test="pic != null" >
- #{pic,jdbcType=VARCHAR},
- if>
- trim>
- insert>
- <update id="updateByPrimaryKeySelective" parameterType="com.zsx.ssm.model.Clazz" >
- update t_struts_class
- <set >
- <if test="cname != null" >
- cname = #{cname,jdbcType=VARCHAR},
- if>
- <if test="cteacher != null" >
- cteacher = #{cteacher,jdbcType=VARCHAR},
- if>
- <if test="pic != null" >
- pic = #{pic,jdbcType=VARCHAR},
- if>
- set>
- where cid = #{cid,jdbcType=INTEGER}
- update>
- <update id="updateByPrimaryKey" parameterType="com.zsx.ssm.model.Clazz" >
- update t_struts_class
- set cname = #{cname,jdbcType=VARCHAR},
- cteacher = #{cteacher,jdbcType=VARCHAR},
- pic = #{pic,jdbcType=VARCHAR}
- where cid = #{cid,jdbcType=INTEGER}
- update>
-
- <select id="listPager" resultType="com.zsx.ssm.model.Clazz" parameterType="com.zsx.ssm.model.Clazz" >
- select
- <include refid="Base_Column_List" />
- from t_struts_class
- <where>
- <if test="cname != null and cname != ''">
- and cname like CONCAT('%',#{cname},'%')
- if>
- <if test="cid !=null and cid != ''">
- and cid = #{cid}
- if>
- where>
- select>
-
-
- <select id="listMapPager" resultType="java.util.Map" parameterType="com.zsx.ssm.model.Clazz">
- select
- <include refid="Base_Column_List" />
- from t_struts_class
- <where>
- <if test="cname != null and cname != ''">
- and cname like CONCAT('%',#{cname},'%')
- if>
- <if test="cid !=null and cid != ''">
- and cid = #{cid}
- if>
- where>
- select>
-
- mapper>
- package com.zsx.ssm.controller;
-
- import com.zsx.ssm.biz.ClazzBiz;
- import com.zsx.ssm.model.Clazz;
- import com.zsx.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 org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author zsx
- * @site 155954····
- * @company 交换余生
- * @create 2022--08--22 16:28
- * 注:@RestController = @ResponseBody + @Controller
- */
- @ResponseBody
- //@Controller
- //@RestController
- @RequestMapping("/json")
- public class JsonController {
- @Autowired
- private ClazzBiz clazzBiz;
-
-
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.list");
- return "clzEdit";
- }
-
-
-
- @RequestMapping("/list")
- public List
list(HttpServletRequest request ,Clazz clazz){ - PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // if (true)
- // throw new RuntimeException("查询班级信息 异常出现在 JsonController.list...");
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- @RequestMapping("/listMap")
- public List
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- @RequestMapping("/map")
- public Map map(HttpServletRequest request , Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request , Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // if(true)
- // throw new RuntimeException("系统繁忙,请参考007");
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest request , Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map=new HashMap();
- map.put("lst",lst);
- map.put("pageBean",pageBean);
- return map;
- }
-
-
- }
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 16:48
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>测试jsontitle>
- head>
- <body>
- <a href="${pageContext.request.contextPath}/json/list">返回List<T>a><hr>
- <a href="${pageContext.request.contextPath}/json/listMap">返回List<Map>a><hr>
- <a href="${pageContext.request.contextPath}/json/load?cid=1">返回Ta><hr>
- <a href="${pageContext.request.contextPath}/json/map?cid=1">返回Mapa><hr>
- <a href="${pageContext.request.contextPath}/json/hunhe">返回混合a>
- body>
- html>
运行效果:




![]()
SpringMVC的配置文件
- <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>
-
Error.jsp
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 18:27
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>错误页面title>
- head>
- <body>
- ${msg} <br>
- ${ex}
- body>
- html>
- package com.zsx.ssm.exception;
-
- /**
- * @author zsx
- * @site 155954····
- * @company 交换余生
- * @create 2022--08--22 18:33
- */
- 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);
- }
- }
- package com.zsx.ssm.exception;
-
- /**
- * @author zsx
- * @site 155954····
- * @company 交换余生
- * @create 2022--08--22 18:33
- */
- 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);
- }
- }
- // T
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request, Clazz clazz){
- // http://localhost:8080/clz/json/load?cid=2
- // System.out.println("JsonController.list");
- // PageBean pageBean=new PageBean();
- // pageBean.setRequest(request);
- // {}
- if(clazz.getCid()!=null){
- List
lst=this.clazzBiz.listPager(clazz,null); - if(true)
- throw new GlobalException("错误出现在JsonController.load");
- return lst.get(0);
- }
- return null;
- }
GlobalExceptionResolver
- package com.zsx.ssm.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
- import org.springframework.web.servlet.HandlerExceptionResolver;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @author zsx
- * @site 155954····
- * @company 交换余生
- *
- *
- * @create 2022--08--22 18:35
- */
-
- @ControllerAdvice
- public class GlobalExceptionResovler{
-
- @ExceptionHandler//异常处理器
- public ModelAndView handler(Exception e) {
- ModelAndView mv=new ModelAndView();
- mv.setViewName("error");
- if(e instanceof GlobalException){
- GlobalException exception= (GlobalException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","全局异常,GlobalExceptionResovler错误码501");
- }else if(e instanceof RuntimeException){
- RuntimeException exception= (RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","运行异常,GlobalExceptionResovler错误码601");
- }
- return mv;
- }
- }
GlobalExceptionJsonResolver
- package com.zsx.ssm.exception;
-
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.servlet.HandlerExceptionResolver;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @author zsx
- * @site 155954····
- * @company 交换余生
- *
- *
- * @create 2022--08--22 18:35
- * 处理全局异常的解析器
- */
-
- //@Component
- public class GlobalHandlerExceptionResovler 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 exception= (GlobalException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","全局异常,错误码501");
- }else if(e instanceof RuntimeException){
- RuntimeException exception= (RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","运行异常,错误码601");
- }
- return mv;
- }
- }
效果图:
![]()