目录
一、SpringMVC之对JSON的支持
1.JOSN的各种场景
1.1.JSON解析
1.2.导入pom依赖(Jackson)
1.3.配置SpringMVC.xml (配置适配器)
1.4.只使用注解@responseBody能够将任何的数据转成JSON对象
1.4.1.后台代码
③.ClazzBiz
测试
前台
1、返回list对象
编辑 2、返回 List对象
3、返回T对象
4、返回Map对象
5、返回混合对象
二、SpringMVC的全局异常处理
1.为什么要全局异常处理?
2.异常处理思路
3.SpringMVC异常分类
4. 非全局异常问题处理
5、异常处理
5.1、使用SpringMVC自带的简单异常处理器SimpleMappingExceptionResolver
5.2、通过HandlerExceptionResovler接口实现全局异常
测试
5.3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
测试
三、全局异常处理JSON返回
测试
1. 返回List
2. 返回List
json的形式
{}->json对象
[]->json数组
{
mag:"",
code:200,
data:[]
}->json混合对象
SpringMVC框架如何生产上述三种格式的数据
1.导入pom依赖 Jackson
2.配置SpringMVC.xml 配置适配器
作用是JSON数据转换的
3.只使用注解@responseBody能够将任何的数据转成JSON对象
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
text/html;charset=UTF-8
text/json;charset=UTF-8
application/json;charset=UTF-8
在项目中如果全部返回json格式数据就用restController:responseBody+controller = restController
在项目中如果返回json格式数据与跳转页面同时存在,就在返回json格式的方法上添加responseBody注解,在类上添加controller
①.ClazzMapper.xml
cid, cname, cteacher, pic
delete from t_struts_class
where cid = #{cid,jdbcType=INTEGER}
insert into t_struts_class (cid, cname, cteacher,
pic)
values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
#{pic,jdbcType=VARCHAR})
insert into t_struts_class
cid,
cname,
cteacher,
pic,
#{cid,jdbcType=INTEGER},
#{cname,jdbcType=VARCHAR},
#{cteacher,jdbcType=VARCHAR},
#{pic,jdbcType=VARCHAR},
update t_struts_class
cname = #{cname,jdbcType=VARCHAR},
cteacher = #{cteacher,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR},
where cid = #{cid,jdbcType=INTEGER}
update t_struts_class
set cname = #{cname,jdbcType=VARCHAR},
cteacher = #{cteacher,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR}
where cid = #{cid,jdbcType=INTEGER}
②.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
⑤.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
①. 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" %>
测试JSON数据返回
返回list<T>对象
返回list<Map>对象
返回T对象
返回Map对象
返回混合对象
测试结果
系统中异常包括:编译时异常和运行时异常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 listMapPager(Clazz clazz, PageBean pageBean) {
if(true){
throw new RuntimeException("查询班级信息异常,异常存在于ClazzBizImpl.listMapPager... ");
}
return clazzMapper.listMapPager(clazz);
}
测试:
报错在Controller层
报错在Service
编辑配置 Springmvc-Servlet.xml
error
新建一个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" %>
错误信息页面
${ex}
先将上面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" %>
错误信息页面
${mag}
${ex}
运行时异常
全局异常
为了不被第二种方式影响,我们将此注掉,注掉之后,以上的异常处理全部都会失效
新建一个类 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;
}
}
运行时异常
全局异常