目录
1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器
3)使用@ControllerAdvice + @ExceptionHandler
JSON的三种形式:
①、{}----->JSON对象
②、[]------>JSON数组
③、{
msg=" ",
code=" ",
data=[]
}------>对象数组
SpringMVC要如果产生上述的三种形式JSON?
步骤:
1、导入pom.xml依赖
2、配置Springmvc.xml适配器
3、使用注解@responseBody 能够将任何的数据转成json对象
①、pom.xml依赖
- <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>
②、Springmvc.xml适配器
- <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>
③、后端代码编写
先编写在ClazzMapper.xml中编写一个查询的方法
- <select id="listMapPager" resultType="java.util.Map" parameterType="com.mgy.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>
将listMapPager该方法在ClazzMapper、ClazzBiz和ClazzBizImpl中实现出来,重新创建一个新类
- package com.mgy.ssm.controller;
-
- import com.mgy.ssm.biz.ClazzBiz;
- import com.mgy.ssm.model.Clazz;
- import com.mgy.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 云鹤衫
- * @site www.yunheshan.com
- * @company xxx公司
- * @create 2022-08-22 18:51
- */
- @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 req,Clazz clazz){ - PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- // [{},{}]
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- // List
- @ResponseBody
- @RequestMapping("/listMap")
- public List
- PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- // [{},{}]
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- // List
- @ResponseBody
- @RequestMapping("/map")
- public Map map(HttpServletRequest req, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- // {}
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- // T
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- // http://localhost:8080/clz/json/load?cid=2
- PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- // {}
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- /* {
- msg:"",
- code:200,
- data:[],
- pageBean:{}
- }*/
-
- @ResponseBody
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest req, Clazz clazz){
- // http://localhost:8080/clz/json/load?cid=2
- PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map=new HashMap();
- map.put("data",lst);
- map.put("pagebean",pageBean);
- return map;
-
- }
-
- }
④、前端代码编写
index.jsp
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 19:35
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
测试json数据返回
效果:
list方法效果:
listMap方法效果:
load方法效果:
map方法效果:
hunhe方法效果:
在JsonController类上加入@ResController注解
@ResponseBody+@controller=@ResController
Controller层
- @RequestMapping("/list")
- public List
list(HttpServletRequest req,Clazz clazz){ - PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- if(true)
- throw new RuntimeException("查询班级异常,异常存在于JsonController.list方法中");
- // [{},{}]
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- // http://localhost:8080/clz/json/load?cid=2
- PageBean pageBean=new PageBean();
- pageBean.setRequest(req);
- if(true)
- throw new GlobalException("系统繁忙,请参考E007l;");
-
- // {}
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
Service层
- @Override
- public List
- if(true)
- throw new RuntimeException("查询班级异常,ClazzBizImpl.list方法中");
- return clazzMapper.listMapPager(clazz);
- }
效果:
点击图上两个方法
返回list
返回list
配置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/23
- Time: 18:25
- 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中关于异常处理的配置取消掉
先建立一个类作为全局异常类
- package com.mgy.ssm.exception;
-
- /**
- * @author 云鹤衫
- * @site www.yunheshan.com
- * @company xxx公司
- * @create 2022-08-23 18:30
- */
- 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.mgy.ssm.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author 云鹤衫
- * @site www.yunheshan.com
- * @company xxx公司
- * @create 2022-08-23 19:09
- */
- @ControllerAdvice
- public class GlobalExceptionHandler {
-
- @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","全局异常,GlobalExceptionHandler,错误码501");
- }else if(e instanceof RuntimeException){
- RuntimeException exception=(RuntimeException)e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","运行时异常,GlobalExceptionHandler,错误码601");
- }
- return mv;
- }
- }
效果:
将之前异常处理器上的注解注销
然后重新建立一个异常处理器
- package com.mgy.ssm.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author 云鹤衫
- * @site www.yunheshan.com
- * @company xxx公司
- * @create 2022-08-23 19:09
- *
- * 当出现异常,统一向前端响应错误信息的json对象数据
- */
- //@ControllerAdvice
- public class GlobalExceptionHandler2 {
-
- @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","全局异常,GlobalExceptionHandler,错误码501");
- }else if(e instanceof RuntimeException){
- RuntimeException exception=(RuntimeException)e;
- map.put("ex",exception.getMessage());
- map.put("msg","运行时异常,GlobalExceptionHandler,错误码601");
- }
- return map;
- }
- }
效果: