目录
{}->json对象 T Map
[]-> json数组 ListList
1,导入pom依赖 jackson(让SpringMVC支持json数据转换)
-
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-databindartifactId>
- <version>2.9.3version>
-
- <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>
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">
-
- <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>
3.使用注解@responseBody 能够将任何的数据转换为json对象
在Biz层中写出以下几个方法:
1.返回List
2.返回List
3.返回T
4.返回Map
5.返回混合
ClazzBiz:
- package com.ljj.ssm.biz;
-
- import com.ljj.model.Clazz;
- import com.ljj.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中添加方法:
- @Override
- public List
- return clazzMapper.listMapPager(clazz);
- }
ClazzMapper:
List <Map> listMapPager(Clazz clazz);
ClazzMapper.xml:
-
- select
-
"Base_Column_List" /> - from t_struts_class
-
- <if test="cname !=null and cname !=''">
- and cname like concat('%')
- if>
- <if test="cid !=null and cid !=''">
- and cid = #{cid}
- if>
-
- order by cid desc
-
JsonController :
- package com.ljj.controller;
-
- import com.ljj.model.Clazz;
- import com.ljj.ssm.biz.ClazzBiz;
- import com.ljj.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- //@ResponseBody+@Controller=@RestController
-
- @RestController
- @RequestMapping("/clz/json")
- public class JsonController {
- @Autowired
- private ClazzBiz clazzBiz;
-
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- /**
- * list
- */
- @RequestMapping("/list")
- public List<Clazz> list(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // [{},{}]
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- /**
- * list
- */
- @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);
- }
-
- // 返回一个T对象
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- // {}
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- // 混合
- // {
- // msg:" ",
- // code:200,
- // data:[ ]
- // }
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest request, Clazz clazz){
- 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;
- }
-
- }
index.jsp:
- <%--
- Created by IntelliJ IDEA.
- User: zjjt
- Date: 2022/8/22
- Time: 18:42
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
- <head>
- <title>测试json数据返回title>
- head>
- <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对象

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

点击list

点击list

此时可以看到,两个异常 一个在控制层,一个在业务层,这样很不方便维护
2.异常处理思路?
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
3.SpringMVC异常分类
1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;
3)使用@ControllerAdvice + @ExceptionHandler
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>
新建一个error.jsp页面:
- <%--
- Created by IntelliJ IDEA.
- User: zjjt
- Date: 2022/8/23
- Time: 14:11
- 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>
再次运行:

当点击“返回list
当点击“返回list<>Map对象”时:
GlobalException :
- package com.ljj.exception;
-
- /**
- * @author ljj
- * @create 2022-08-23 14:24
- */
- 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.ljj.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 ljj
- * @create 2022-08-23 14:31
- * 处理全局异常的解析器
- */
-
- @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;
- }
- }
JsonController:
- // 返回一个T对象
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest request, Clazz clazz){
- PageBean pageBean=new PageBean();
- pageBean.setRequest(request);
- if(true) {
- throw new GlobalException("系统繁忙,请参考E007;");
- }
- // {}
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
error.jsp
- <%--
- Created by IntelliJ IDEA.
- User: zjjt
- Date: 2022/8/23
- Time: 14:11
- 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>
运行效果:

当点击“返回list

当点击“返回list<>Map对象”时:

当点击“返回T对象”时:

当点击“返回Map对象”时:

- package com.ljj.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author ljj
- * @create 2022-08-23 15:00
- */
- @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<>Map对象”时:

当点击“返回T对象”时:

当点击“返回Map对象”时:

GlobalExceptionResolver2 :
- package com.ljj.exception;
-
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author ljj
- * @create 2022-08-23 15:00
- *
- * 当出现异常,统一向前端相应错误信息的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;
-
- }
-
-
- }
当点击“返回list

当返回list

当点击“返回T对象”时:

当点击“返回Map对象”时:

ok,本期内容到此结束啦,我们下期见