目录
Json的形式
{ } ->json对象
[ ] ->json数组
{
msg : " "
code : 200
data : [ ]
} ->json 混合对象
1、Springmvc框架如何产生上述三种格式的数据:
1.1导入pom依赖
- <!--用来 Springmvc 支持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>
1.2 配置Springmvc.xml
- <!--支持 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>
ClazzMapper.xml:
- <select id="listMapPager" resultType="java.util.Map" parameterType="com.zxw.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>
ClazzMapper:
List
ClazzBizImpl:
- @Override
- public List<Map> listMapPager(Clazz clazz, PageBean PageBea) {
- return ClazzMapper.listMapPager(clazz);
- }
建一个JsonController:
- package com.zxw.ssm.controller;
-
- import com.zxw.ssm.biz.ClazzBiz;
- import com.zxw.ssm.model.Clazz;
- import com.zxw.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 zxw
- * @site ......
- * @company 好男人
- * @create 2022-08-22 16:23
- */
- @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<T>
- @ResponseBody
- @RequestMapping("/list")
- public List<Clazz> list(HttpServletRequest request, Clazz clazz) {
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- // [{},{}]
- return this.clazzBiz.listPager(clazz, pageBean);
- }
-
- // list<Map>
- @ResponseBody
- @RequestMapping("/listMap")
- public List<Map> listMap(HttpServletRequest request, Clazz clazz) {
- 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) {
- // http://localhost:8080/clz/json/load?cid=2
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- // {}
- return this.clazzBiz.listPager(clazz, pageBean).get(0);
- }
-
-
- // {
- // mag:"",
- // code:200,
- // data:[],
- // PageBean:{}
- //}
-
- @ResponseBody
- @RequestMapping("/hunhe")
- public Map huihe(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("data",lst);
- map.put("pagebean",pageBean);
- return map;
-
- // return this.clazzBiz.listPager(clazz, pageBean).get(0);
- }
-
-
-
-
- }
最后建一个index界面:
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 18: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">返回<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>
- </body>
- </html>
测试结果:

返回list

返回list

返回T对象:

返回Map对象:

返回混合对象:

1.为什么要全局异常处理:
我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。
JsonController:
- // list
- @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);
- }
ClazzBizImpl:
- @Override
- public List<Map> listMapPager(Clazz clazz, PageBean PageBea) {
- if(true)
- throw new RuntimeException("查询班级信息异常、异常存在于ClazzBizImpl.list...");
- return ClazzMapper.listMapPager(clazz);
- }
测试:

点击这两个分别对应的报错如下所示


全局处理异常的三种方式:
SpringMVC自带的简单异常处理器
springmvc.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>
-
新建一个crror.jsp页面:
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 19:55
- 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>
测试:

通过HandlerExceptionResovler接口实现全局异常
全局异常GlobalException:
- package com.zxw.ssm.exception;
-
- /**
- * @author zxw
- * @site ......
- * @company 好男人
- * @create 2022-08-22 20:14
- */
- 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);
- }
- }
异常处理器 GlobalHandlerExceptionResovler:
- package com.zxw.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 zxw
- * @site ......
- * @company 好男人
- * @create 2022-08-22 20:16
- *
- * 处理全局异常的解析器
- */
- @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;
- }
-
- }
测试代码controller层的改变
- @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);
- }
测试:

返回list

返回list

返回T对象:
全局异常处理JSON返回
我们新建一个
GlobalExceptionResolver:
- package com.zxw.ssm.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author zxw
- * @site ......
- * @company 好男人
- * @create 2022-08-22 22:05
- */
- @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;
-
- }
- }
再次进行测试:

list
list

T对象:
我是呲花 今天分享到这!