目录
json的形式
- <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>
- <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>
在这里说明:
项目中如果这个控制类返回json格式数据与跳转页面同时存在,就在返回json格式的方法上添加responseBody注解,在类上添加controller注释;
而如果这个控制类只需要返回JSON格式数据的话就在就直接在类上面添加restController注释(responseBody+controller = restController)
- package com.zq.ssm.controller;
-
- import com.zq.ssm.biz.ClazzBiz;
- import com.zq.ssm.model.Clazz;
- import com.zq.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;
-
- /**
- * @author张强
- * @site www.zq.com
- * @create 2022-08-24 8:57
- */
- @RestController
- @RequestMapping("/clz/json")
- public class JSONController {
- @Autowired
- private ClazzBiz clazzBiz;
-
- //返回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("/Clazz")
- public Clazz clazz(HttpServletRequest Request , Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(Request);
- //返回[{},{}]
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- //返回list
- @RequestMapping("/list")
- public List
list(HttpServletRequest Request , Clazz clazz){ - PageBean pageBean = new PageBean();
- pageBean.setRequest(Request);
- //返回[{},{}]
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- //返回list
- @RequestMapping("/listMap")
- public List
- PageBean pageBean = new PageBean();
- pageBean.setRequest(Request);
- //返回[{},{}]
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- //返回对象数组
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest Request , Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(Request);
- //返回[{},{}]
- List
list = this.clazzBiz.listPager(clazz,pageBean); - Map map = new HashMap();
- map.put("list",list);
- map.put("pageBean",pageBean);
- return map;
- }
-
- }
- <%--
- Created by IntelliJ IDEA.
- User: zjjt
- Date: 2022/8/22
- Time: 18:47
- 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">返回List<T>a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/listMap">返回List<Map>a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/Clazz?cid=1">返回Ta><hr>
- <a href="${pageContext.request.contextPath}/clz/json/Map?cid=1">返回Mapa><hr>
- <a href="${pageContext.request.contextPath}/clz/json/hunhe">返回混合a><hr>
- body>
- html>
我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
2)实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;
3)使用@ControllerAdvice + @ExceptionHandler
- <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/24
- Time: 10:21
- 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>
- package com.zq.ssm.exception;
-
- /**
- * @author张强
- * @site www.zq.com
- * @create 2022-08-24 10:35
- */
- 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.zq.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张强
- * @site www.zq.com
- * @create 2022-08-24 10:36
- */
- @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.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.zq.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.zq.com
- * @create 2022-08-24 10:54
- */
- @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;
- }
- }
在上述的三中方式中,都是通过跳转页面的方式,但是在项目开发中还是通过JSON数据传递的方式才行,所以我们再次修改一下我们的异常处理,把它编译为JSON数据传递的方式:
- @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;
- }
- }