目录
2.2、通过HandlerExceptionResovler接口实现全局异常
2.3、使用@controllerAdvice+@ExceptionHandler实现全局异常处理
- 1.1返回List
- 1.2返回List
- 1.3返回T
- 1.4返回Map
- 1.5返回混合
- 1.6返回JSON字符串
- <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>
-
- <!--支持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">
- <!--处理中文乱码以及避免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>
- package com.ssr.ssm2.biz;
-
- import com.ssr.ssm2.model.Clazz;
- import com.ssr.ssm2.uitl.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);
-
- List
listPager(Clazz clazz, PageBean pageBean); -
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
-
- List
-
- }
- package com.ssr.ssm2.biz.impl;
-
- import com.ssr.ssm2.biz.ClazzBiz;
- import com.ssr.ssm2.mapper.ClazzMapper;
- import com.ssr.ssm2.model.Clazz;
- import com.ssr.ssm2.uitl.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author四金
- * @site 2261696885
- * @company 浪琴湾总公司
- * @create 2022-08-17-19:27
- */
- @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 clazz, PageBean pageBean) { - return clazzMapper.listPager(clazz);
- }
-
- @Override
- public int updateByPrimaryKeySelective(Clazz record) {
- return clazzMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(Clazz record) {
- return clazzMapper.updateByPrimaryKey(record);
- }
-
- @Override
- public List
- if(true)
- throw new RuntimeException("查询班级信息异常、异常存在于ClazzBizImpl.list方法中");
- return clazzMapper.listMapPager(clazz);
- }
- }
- package com.ssr.ssm2.mapper;
-
- import com.ssr.ssm2.model.Clazz;
- 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 clazz); -
- List
-
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.ssr.ssm2.mapper.ClazzMapper" >
- <resultMap id="BaseResultMap" type="com.ssr.ssm2.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>
-
- <select id="listPager" resultType="com.ssr.ssm2.model.Clazz" parameterType="com.ssr.ssm2.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.ssr.ssm2.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>
-
-
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
- delete from t_struts_class
- where cid = #{cid,jdbcType=INTEGER}
- </delete>
- <insert id="insert" parameterType="com.ssr.ssm2.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.ssr.ssm2.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.ssr.ssm2.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.ssr.ssm2.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>
- </mapper>
- package com.ssr.ssm2.controller;
-
- import com.ssr.ssm2.biz.ClazzBiz;
- import com.ssr.ssm2.exception.GlobalException;
- import com.ssr.ssm2.model.Clazz;
- import com.ssr.ssm2.uitl.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author四金
- * @site 2261696885
- * @company 浪琴湾总公司
- * @create 2022-08-22-16:34
- */
- @Controller
- @RequestMapping("/clz/json")
- public class JsonController {
- @Autowired
- private ClazzBiz clazzBiz;
-
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- // list<T>的格式
- @RequestMapping("/list")
- public List<Clazz> 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);
- }
-
- // list<Map>的格式
- @RequestMapping("/listMap")
- public List<Map> listMap(HttpServletRequest request, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- // [{},{}]
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- // map的格式
- @RequestMapping("/map")
- public Map map(HttpServletRequest request, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- // [{},{}]
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- // map的格式
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request, Clazz clazz){
- // http://localhost:8080/clz/json/load?cid=2
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- if(true)
- throw new GlobalException("系统繁忙,请参考E007;");
- // [{},{}]
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- // {
- // msg:"",
- // code:200,
- // data:[]
- // pageBean:{}
- // }
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest request, Clazz clazz){
- // http://localhost:8080/clz/json/load?cid=2
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
- Map map = new HashMap();
- map.put("date",lst);
- map.put("pagebean",pageBean);
- return map;
- }
- }
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 17:14
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>测试json数据返回</title>
- </head>
- <body>
- <a href="${pageContext.request.contextPath}/clz/json/list">返回list<T>对象</a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/listMap">返回list<Map>对象</a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回T对象</a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/map?cid=1">返回map对象</a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/hunhe">返回混合对象</a><hr>
- </body>
- </html>
返回list
返回list
返回T对象
返回 map对象
返回混合对象
- <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: 19:15
- 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}
- <hr>
- ${ex}
- </body>
- </html>
- package com.ssr.ssm2.exception;
-
- /**
- * @author四金
- * @site 2261696885
- * @company 浪琴湾总公司
- * @create 2022-08-22-19:44
- */
- 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.ssr.ssm2.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四金
- * @site 2261696885
- * @company 浪琴湾总公司
- * @create 2022-08-22-19:28
- *
- * 处理全局异常的解析器
- *
- */
- //@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 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;
- }
- }
- // 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<Clazz> lst=this.clazzBiz.listPager(clazz,null);
- if(true)
- throw new GlobalException("错误出现在JsonController.load");
- return lst.get(0);
- }
- return null;
- }
- package com.ssr.ssm2.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author四金
- * @site 2261696885
- * @company 浪琴湾总公司
- * @create 2022-08-22-19:56
- */
- //@ControllerAdvice
- public class GlobalExceptionResolver {
- @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","全局异常,GlobalExceptionResolver错误码501");
- }
- else if(e instanceof RuntimeException){
- RuntimeException exception = (RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","运行时异常,GlobalExceptionResolver错误码601");
- }
- return mv;
- }
- }
- package com.ssr.ssm2.exception;
-
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
- import org.springframework.web.servlet.ModelAndView;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author四金
- * @site 2261696885
- * @company 浪琴湾总公司
- * @create 2022-08-22-19:56
- *
- * 档出现异常,统一想前端响应错误信息的json对象数据
- */
- @RestControllerAdvice
- public class GlobalExceptionResolver2 {
- // @ExceptionHandler
- public Map handler(Exception e){
- Map map = new HashMap();
- if(e instanceof GlobalException){
- GlobalException exception = (GlobalException) e;
- map.put("ex",exception.getMessage());
- map.put("msg","全局异常,GlobalExceptionResolver错误码501");
- }
- else if(e instanceof RuntimeException){
- RuntimeException exception = (RuntimeException) e;
- map.put("ex",exception.getMessage());
- map.put("msg","运行时异常,GlobalExceptionResolver错误码601");
- }
- return map;
- }
- }
运行结果: