目录
1.4.只使用注解@responseBody能够将任何的数据转成JSON对象
5.1、使用SpringMVC自带的简单异常处理器SimpleMappingExceptionResolver
5.2、通过HandlerExceptionResovler接口实现全局异常
5.3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
1. 返回List
2. 返回List
- json的形式
- {}->json对象
- []->json数组
- {
- mag:"",
- code:200,
- data:[]
- }->json混合对象
SpringMVC框架如何生产上述三种格式的数据
1.导入pom依赖 Jackson
2.配置SpringMVC.xml 配置适配器
作用是JSON数据转换的
3.只使用注解@responseBody能够将任何的数据转成JSON对象
- <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>
在项目中如果全部返回json格式数据就用restController:responseBody+controller = restController
在项目中如果返回json格式数据与跳转页面同时存在,就在返回json格式的方法上添加responseBody注解,在类上添加controller
①.ClazzMapper.xml
- "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.oyang.ssm.mapper.ClazzMapper" >
- <resultMap id="BaseResultMap" type="com.oyang.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" resultType="com.oyang.ssm.model.Clazz" parameterType="com.oyang.ssm.model.Clazz" >
- select
- <include refid="Base_Column_List" />
- from t_struts_class
- where cid = #{cid,jdbcType=INTEGER}
- select>
-
- <select id="listPager" resultType="com.oyang.ssm.model.Clazz" parameterType="com.oyang.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.oyang.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>
-
-
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
- delete from t_struts_class
- where cid = #{cid,jdbcType=INTEGER}
- delete>
- <insert id="insert" parameterType="com.oyang.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.oyang.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.oyang.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.oyang.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>
- mapper>
②.ClazzMapper.java
- package com.oyang.ssm.mapper;
-
- import com.oyang.ssm.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);
-
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
-
- List
listPager(Clazz clazz); -
- List
-
-
- }
- package com.oyang.ssm.biz;
-
- import com.oyang.ssm.model.Clazz;
- import com.oyang.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 clazz, PageBean pageBean); -
- List
-
-
- }
④.ClazzBizImpl
- package com.oyang.ssm.impl;
-
- import com.oyang.ssm.biz.ClazzBiz;
- import com.oyang.ssm.mapper.ClazzMapper;
- import com.oyang.ssm.model.Clazz;
- import com.oyang.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author oyang
- * @site https://blog.csdn.net
- * @qq 1828190940
- * @create 2022-08-17 20:59
- */
- @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 int updateByPrimaryKeySelective(Clazz record) {
- return clazzMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(Clazz record) {
- return clazzMapper.updateByPrimaryKey(record);
- }
-
- @Override
- public List
listPager(Clazz clazz, PageBean pageBean) { - return clazzMapper.listPager(clazz);
- }
-
- @Override
- public List
- return clazzMapper.listMapPager(clazz);
- }
- }
⑤.JsonController
- package com.oyang.ssm.aspect;
-
- import com.oyang.ssm.biz.ClazzBiz;
- import com.oyang.ssm.model.Clazz;
- import com.oyang.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 oyang
- * @site https://blog.csdn.net
- * @qq 1828190940
- * @create 2022-08-22 17:38
- */
- @Controller
- @RequestMapping("/clz/json")
- public class JsonController {
-
- @Autowired
- private ClazzBiz clazzBiz;
-
- @ResponseBody
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- // list
- @ResponseBody
- @RequestMapping("/list")
- public List
list(HttpServletRequest request,Clazz clazz){ - PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // [{},{}]
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- // list
- @ResponseBody
- @RequestMapping("/listMap")
- public List
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // [{},{}]
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- // Map
- @ResponseBody
- @RequestMapping("/map")
- public Map map(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // {}
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- // T
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // {}
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
-
- // Map
- //{
- // mag:"",
- // code:200,
- // data:[],
- //PageBean:{}
- //}
- @ResponseBody
- @RequestMapping("/hunh")
- public Map hunh(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // {}
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map=new HashMap();
- map.put("data",lst);
- map.put("pagebean",pageBean);
- return map;
- // return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
- }
①. index.jsp
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/23
- Time: 17:02
- 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/hunh">返回混合对象a><hr>
-
- body>
- html>
测试结果
系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;
3)使用@ControllerAdvice + @ExceptionHandler
在控制层Controller添加异常代码
- @ResponseBody
- @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);
- }
在业务层implements添加异常代码
- @Override
- public List
- if(true){
- throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.listMapPager... ");
- }
- return clazzMapper.listMapPager(clazz);
- }
测试:
报错在Controller层
报错在Service
编辑配置 Springmvc-Servlet.xml
- <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>
新建一个jsp页面,收集错误信息
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/23
- Time: 14:00
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>错误信息页面title>
- head>
- <body>
- ${ex}
- body>
- html>
先将上面Springmvc-Servlet.xml中关于异常处理的配置取消掉
新建GlobalException类:
- package com.oyang.ssm.exception;
-
- /**
- * @author oyang
- * @site https://blog.csdn.net
- * @qq 1828190940
- * @create 2022-08-23 14:23
- */
- 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);
- }
- }
全局异常处理器 GlobalHanderExceptionResovler
- package com.oyang.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 oyang
- * @site https://blog.csdn.net
- * @qq 1828190940
- * @create 2022-08-23 14:30
- *
- * 处理全局异常的解析器
- */
- @Component
- public class GlobalHanderExceptionResovler 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("mag","全局异常,错误码502");
- }else if(e instanceof RuntimeException){
- RuntimeException exception=(RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("mag","运行时异常,错误码602");
- }
- return mv;
- }
- }
测试代码controller层的改变,改变load方法
- // T
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- if(true){
- throw new GlobalException("系统繁忙·请参考Y001");
- }
- // {}
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
提示错误界面
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/23
- Time: 14:00
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>错误信息页面title>
- head>
- <body>
- ${mag}
- <hr>
- ${ex}
- body>
- html>
运行时异常
全局异常
为了不被第二种方式影响,我们将此注掉,注掉之后,以上的异常处理全部都会失效
新建一个类 GlobalExceptionResolver
- package com.oyang.ssm.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author oyang
- * @site https://blog.csdn.net
- * @qq 1828190940
- * @create 2022-08-23 14:57
- */
- @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("mag","全局异常 GlobalExceptionResolver,错误码502");
- }else if(e instanceof RuntimeException){
- RuntimeException exception=(RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("mag","运行时异常 GlobalExceptionResolver,错误码602");
- }
- return mv;
- }
- }
运行时异常
全局异常
在以后的开发中我们肯定是需要将错误码返回JSON格式,而不是跳转页面
还是老样子,我们将注解注掉
新建一个 GlobalExceptionResolver2 类
- package com.oyang.ssm.exception;
-
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author oyang
- * @site https://blog.csdn.net
- * @qq 1828190940
- * @create 2022-08-23 14:57
- *
- * 当出现异,统一向前端响应错误信息的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("mag","全局异常 GlobalExceptionResolver,错误码502");
- }else if(e instanceof RuntimeException){
- RuntimeException exception=(RuntimeException) e;
- map.put("ex",exception.getMessage());
- map.put("mag","运行时异常 GlobalExceptionResolver,错误码602");
- }
- return map;
- }
- }
运行时异常
全局异常