上一次分享了jsr303 以及 拦截器。 本次分享的内容为,JSON 以及全局异常的处理
1、JSON的各种场景
1、返回List
2、返回List
3、返回T
4、返回Map
5、返回混合
2、pom依赖
导入pom依赖
- <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>
3、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>
4、后台代码
JsonController
- package com.zhw.web;
-
- import com.zhw.biz.ClazzBiz;
- import com.zhw.model.Clazz;
- import com.zhw.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 louis
- * @create 2022-08-22 20:18
- */
- @Controller
- @RequestMapping("/clz/json")
- public class JsonController {
- @Autowired
- private ClazzBiz clazzBiz;
-
- /**
- * 返回List
- * @param req
- * @param clazz
- * @return
- */
- @ResponseBody
- @RequestMapping("/list")
- public List
list(HttpServletRequest req, Clazz clazz){ - PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - return lst;
- }
-
- /**
- * 返回T
- * @param req
- * @param clazz
- * @return
- */
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- if(clazz.getCid() != null){
- List
lst = this.clazzBiz.listPager(clazz, null); - return lst.get(0);
- }
- return null;
- }
-
-
- /**
- * 返回List
- * @param req
- * @param clazz
- * @return
- */
- @ResponseBody
- @RequestMapping("/mapList")
- public List
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- // List
- // return lst;
- return null;
- }
-
- /**
- * 返回Map
- * @param req
- * @param clazz
- * @return
- */
- @ResponseBody
- @RequestMapping("/mapLoad")
- public Map mapLoad(HttpServletRequest req, Clazz clazz){
- if(clazz.getCid() != null){
- List
- return lst.get(0);
- }
- return null;
- }
-
-
- @ResponseBody
- @RequestMapping("/all")
- public Map all(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map = new HashMap();
- map.put("lst",lst);
- map.put("pageBean",pageBean);
- return map;
- }
-
- @ResponseBody
- @RequestMapping("/jsonStr")
- public String jsonStr(HttpServletRequest req, Clazz clazz){
- return "clzEdit";
- }
-
-
- }
mapper.xml
- <select id="mapListPager" parameterType="com.zhw.model.Clazz" resultType="java.util.Map">
- select
- <include refid="Base_Column_List" />
- from t_struts_class
- <where>
- <if test="cname != null and cname != ''">
- cname like CONCAT('%',#{cname},'%')
- if>
- <if test="cid != null and cid != ''">
- cid = #{cid}
- if>
- where>
- select>
5、前台代码
- <body>
- <h3>JSONh3>
- <a href="${pageContext.request.contextPath}/clz/json/list">返回List<T>a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/mapList">返回List<Map>a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回Ta><hr>
- <a href="${pageContext.request.contextPath}/clz/json/mapLoad?cid=1">返回Mapa><hr>
- <a href="${pageContext.request.contextPath}/clz/json/all">返回混合a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/jsonStr">返回JSON字符串a><hr>
- body>
6、效果展示
1、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>
-
2、后台代码
ClazzBizImpl
- @Override
- public List
- if (true)
- throw new RuntimeException("错误出现在 ClazzBizImpl.mapListPager...");
- return clazzMapper.mapListPager(clazz);
- }
-
Controller
- @ResponseBody
- @RequestMapping("/list")
- public List
list(HttpServletRequest req, Clazz clazz){ - PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- if (true)
- throw new RuntimeException("错误出现在 JsonController.list...");
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - return lst;
- }
- <%--
- Created by IntelliJ IDEA.
- User: Administrator
- Date: 2022/8/22
- Time: 20:32
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Titletitle>
- head>
- <body>
- ${ex}
- body>
- html>
-
3、效果演示
先将上面SpringMVC中关于异常处理的配置取消掉
1、GlobalException
- package com.zhw.exception;
-
- /**
- * @author louis
- * @create 2022-08-22 20:47
- */
- public class GlobalException extends RuntimeException{
- public GlobalException() {
- super();
- }
-
- public GlobalException(String message) {
- super(message);
- }
-
- public GlobalException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public GlobalException(Throwable cause) {
- super(cause);
- }
-
- protected GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
- }
2、GlobalExceptionHandler
- package com.zhw.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 louis
- * @create 2022-08-22 20:49
- */
- @Component
- public class GlobalExceptionHandler implements HandlerExceptionResolver {
- @Override
- public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
- ModelAndView mv=new ModelAndView();
- mv.setViewName("error");
- if(e instanceof GlobalException){
- GlobalException globalException = (GlobalException) e;
- mv.addObject("ex",globalException);
- mv.addObject("msg","全局异常。。。");
- }else if(e instanceof RuntimeException){
- RuntimeException runtimeException = (RuntimeException) e;
- mv.addObject("ex",runtimeException.getMessage());
- mv.addObject("msg","运行时异常。。。");
- }
- return mv;
- }
- }
3、controller
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- if(clazz.getCid() != null){
- List
lst = this.clazzBiz.listPager(clazz, null); - return lst.get(0);
- }
- return null;
- }
4、效果
- package com.zhw.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author louis
- * @create 2022-08-22 20:59
- */
- @ControllerAdvice
- public class GlobalExceptionResolver {
- @ExceptionHandler
- public ModelAndView handler(Exception e){
- ModelAndView mv = new ModelAndView();
- mv.setViewName("error");
- if(e instanceof GlobalException){
- GlobalException globalException = (GlobalException) e;
- mv.addObject("ex",globalException.getMessage());
- mv.addObject("msg","全局异常");
- }else if(e instanceof RuntimeException){
- RuntimeException runtimeException = (RuntimeException) e;
- mv.addObject("ex",runtimeException.getMessage());
- mv.addObject("msg","运行时异常..");
- }
- return mv;
- }
- }
- package com.zhw.exception;
-
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author louis
- * @create 2022-08-22 21:02
- */
- @RestControllerAdvice
- public class GlobalExceptionJsonResolver {
- @ExceptionHandler
- public Map handler(Exception e){
- Map map = new HashMap();
- if(e instanceof GlobalException){
- GlobalException globalException = (GlobalException) e;
- map.put("ex",globalException.getMessage());
- map.put("msg","全局异常");
- }else if(e instanceof RuntimeException){
- RuntimeException runtimeException = (RuntimeException) e;
- map.put("ex",runtimeException.getMessage());
- map.put("msg","运行时异常");
- }
- return map;
- }
- }