一.什么是SpringMVC之JSON返回&异常处理机制
二.Json处理
导入pom.xml依赖
导入Spring-Mvc.xml
编写JsonController
编写Sql语句
测试结果
json转换的注解
测试结果(@JsonIgnore)
三.全局异常处理机制
为什么要全局异常处理
异常处理思路
编辑
自写一个错误代码
编辑 输出结果
异常处理方式(一)
新建一个erreo.jsp
输出结果
异常处理(二)
编写GlobalException类
编写全局异常处理类GlobalExceptionHandler
在error.jsp中编写
在JsonController类编写异常
测试结果
编辑 异常处理(三)
编写GlobalExceptionResolver类
测试结果
重新编写GlobalExceptionResolver类
测试结果
SpringMVC是一个Web框架,它提供了许多方便的特性,其中之一就是JSON返回和异常处理机制。
JSON返回指的是,当客户端向服务器发起请求时,服务器可以返回JSON格式的响应数据。这是非常常见的一种情况,特别是在前后端分离的开发模式中,后端通常会返回JSON格式的数据。
SpringMVC提供了多种方式来实现JSON返回,其中最简单的方式是使用@ResponseBody注解,这个注解可以将Controller方法返回的对象自动转换成JSON格式的数据,然后响应给客户端。如果需要更加灵活的JSON格式化方式,可以使用Jackson或者FastJSON等库进行定制化配置。
异常处理机制指的是当服务器出现异常时,SpringMVC提供了一套通用的异常处理机制,可以统一处理异常,返回友好的错误信息给客户端。在SpringMVC中,异常处理主要分为两种方式,一种是基于@ControllerAdvice注解的全局异常处理方式,另一种是基于@ExceptionHandler注解的局部异常处理方式。通过这两种方式,我们可以针对不同的异常类型进行不同的处理,比如返回特定的错误码、错误信息等。这样可以提高系统的容错性和可靠性。
4.0.0
org.example
xyzy
1.0-SNAPSHOT
war
xyzy Maven Webapp
http://www.example.com
UTF-8
1.8
1.8
3.7.0
5.0.2.RELEASE
3.4.5
5.1.44
5.1.2
1.3.1
2.1.1
2.4.3
2.9.1
3.2.0
1.7.13
4.12
4.0.0
1.18.2
1.1.0
2.10.0
2.9.0
1.7.1.RELEASE
2.9.3
1.2
1.1.2
8.0.47
1.3.3
5.0.2.Final
1.3.2
org.springframework
spring-core
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-aspects
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-test
${spring.version}
org.mybatis
mybatis
${mybatis.version}
mysql
mysql-connector-java
${mysql.version}
com.github.pagehelper
pagehelper
${pagehelper.version}
org.mybatis
mybatis-spring
${mybatis.spring.version}
org.springframework
spring-context-support
${spring.version}
org.mybatis.caches
mybatis-ehcache
${mybatis.ehcache.version}
net.sf.ehcache
ehcache
${ehcache.version}
redis.clients
jedis
${redis.version}
org.springframework.data
spring-data-redis
${redis.spring.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
org.apache.commons
commons-dbcp2
${commons.dbcp2.version}
commons-pool2
org.apache.commons
org.apache.commons
commons-pool2
${commons.pool2.version}
org.springframework
spring-webmvc
${spring.version}
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
jcl-over-slf4j
${slf4j.version}
runtime
org.apache.logging.log4j
log4j-api
${log4j2.version}
org.apache.logging.log4j
log4j-core
${log4j2.version}
org.apache.logging.log4j
log4j-slf4j-impl
${log4j2.version}
org.apache.logging.log4j
log4j-web
${log4j2.version}
runtime
com.lmax
disruptor
${log4j2.disruptor.version}
junit
junit
${junit.version}
javax.servlet
javax.servlet-api
${servlet.version}
provided
org.projectlombok
lombok
${lombok.version}
provided
jstl
jstl
${jstl.version}
taglibs
standard
${standard.version}
org.apache.tomcat
tomcat-jsp-api
${tomcat-jsp-api.version}
commons-fileupload
commons-fileupload
${commons-fileupload.version}
org.hibernate
hibernate-validator
${hibernate-validator.version}
org.apache.shiro
shiro-core
${shiro.version}
org.apache.shiro
shiro-web
${shiro.version}
org.apache.shiro
shiro-spring
${shiro.version}
xyzy
src/main/java
**/*.xml
src/main/resources
*.properties
*.xml
org.apache.maven.plugins
maven-compiler-plugin
${maven.compiler.plugin.version}
${maven.compiler.source}
${maven.compiler.target}
${project.build.sourceEncoding}
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
mysql
mysql-connector-java
${mysql.version}
true
maven-clean-plugin
3.1.0
maven-resources-plugin
3.0.2
maven-compiler-plugin
3.8.0
maven-surefire-plugin
2.22.1
maven-war-plugin
3.2.2
maven-install-plugin
2.5.2
maven-deploy-plugin
2.8.2
text/html;charset=UTF-8
text/json;charset=UTF-8
application/json;charset=UTF-8
package com.xy.web;
import com.xy.biz.hpjyBiz;
import com.xy.biz.hpjyBiz;
import com.xy.model.hpjy;
import com.xy.utils.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 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.javaxl.com
* @company xxx公司
* @create 2022-08-17 9:41
*/
//@ResponseBody
//@Controller
@RestController
@RequestMapping("/hpjy/json")
public class JsonController {
@Autowired
private hpjyBiz hpjyBiz;
/**
* 返回List
* @param req
* @param hpjy
* @return
*/
// @ResponseBody
@RequestMapping("/list")
public List list(HttpServletRequest req, hpjy hpjy){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List lst = this.hpjyBiz.listPager(hpjy, pageBean);
return lst;
}
/**
* 返回T
* @param req
* @param hpjy
* @return
*/
// @ResponseBody
@RequestMapping("/load")
public hpjy load(HttpServletRequest req, hpjy hpjy){
if(hpjy.getId() != null){
List lst = this.hpjyBiz.listPager(hpjy, null);
return lst.get(0);
}
return null;
}
/**
* 返回List
// @ResponseBody @RequestMapping("/load") public hpjy load(HttpServletRequest req, hpjy hpjy){ if(hpjy.getId() != null){ Listlst = this.hpjyBiz.listPager(hpjy, null); return lst.get(0); } return null; } 测试结果如下:
/** * 返回List* @param req * @param hpjy * @return */ // @ResponseBody @RequestMapping("/mapList") public List mapList(HttpServletRequest req, hpjy hpjy){ PageBean pageBean = new PageBean(); pageBean.setRequest(req); List lst = hpjyBiz.mapListPager(hpjy, pageBean); return lst; } 测试结果如下:
/** * 返回Map * @param req * @param hpjy * @return */ // @ResponseBody @RequestMapping("/mapLoad") public Map mapLoad(HttpServletRequest req, hpjy hpjy){ if(hpjy.getId() != null){ Listlst = this.hpjyBiz.mapListPager(hpjy, null); return lst.get(0); } return null; } 测试结果如下:
// @ResponseBody @RequestMapping("/all") public Map all(HttpServletRequest req, hpjy hpjy){ PageBean pageBean = new PageBean(); pageBean.setRequest(req); Listlst = this.hpjyBiz.listPager(hpjy, pageBean); Map map = new HashMap(); map.put("lst",lst); map.put("pageBean",pageBean); return map; } 测试结果如下:
// @ResponseBody @RequestMapping("/jsonStr") public String jsonStr(HttpServletRequest req, hpjy hpjy){ return "hpjyEdit"; } 测试结果如下:
(注:隐藏想要隐藏的)
我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。
在Spring-Mvc.xml中写异常处理方式
(注:获取异常的xx)
package com.xy.exception;
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.xy.component;
import com.xy.exception.GlobalException;
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;
//全局异常处理类
@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","运行时异常....");
}else {
mv.addObject("ex",e.getMessage());
mv.addObject("msg","其他异常....");
}
return mv;
}
}
package com.xy.component;
import com.xy.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionResolver {
// 返回错误json数据
@ResponseBody
@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","运行时异常....");
}else {
map.put("ex",e.getMessage());
map.put("msg","其它异常....");
}
return map;
}
package com.xy.component;
import com.xy.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
@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;
}