目录
2、通过HandlerExceptionResovler接口实现全局异常
3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
一、SpringMVC对Json的支持
{ }--->json对象、[ ]-->Json数组{
msg:" "
data:[ ]
}
上述三种情况 SpringMVC框架如何才能产生以上三种情况:
1.导入pom依赖
2.配置SprongMVC.xml配置适配器,作用事用来做Json数据转换
3.使用@responseBody能够将任何数据转换成json对象
导入pom依赖
<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>
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">
<!--处理中文乱码以及避免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>
</bean>
二,后台代码
ClazzBiz
package com.zlp.ssm.web;
import com.zlp.ssm.Exception.GlobalException;
import com.zlp.ssm.biz.ClazzBiz;
import com.zlp.ssm.model.Clazz;
import com.zlp.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 bobo
* @site o3oboboz
* @company 聚星有限公司
* @create 2022-08-22 18:21
*/
@ResponseBody
@Controller
@RequestMapping("/clz/json")
public class JsonController {
@Autowired
private ClazzBiz clazzBiz;
/**
* 返回List<T>
* @param req
* @param clazz
* @return
*/
@RequestMapping("/list")
public List<Clazz> list(HttpServletRequest req, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
if(true) {
throw new RuntimeException("查询班级信息异常,异常存在于JsonController.list方法");
}
List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
return lst;
}
/**
* 返回T
* @param req
* @param clazz
* @return
*/
/*@RequestMapping("/load")
public Clazz load(HttpServletRequest req, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
if(true){
throw new GlobalException("系统繁忙,请参考E007;");
}
return this.clazzBiz.listPager(clazz,pageBean).get(0);
}*/
@RequestMapping("/load")
public Clazz load(HttpServletRequest req, Clazz clazz){
if(clazz.getCid() != null){
List<Clazz> lst = this.clazzBiz.listPager(clazz, null);
if (true)
throw new GlobalException("错误出现在 JsonController.load...");
return lst.get(0);
}
return null;
}
/**
* 返回List<Map>
* @param req
* @param clazz
* @return
*/
@RequestMapping("/mapList")
public List<Map> mapList(HttpServletRequest req, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map> lst = this.clazzBiz.listMapPager(clazz, pageBean);
return lst;
}
/**
* 返回Map
* @param req
* @param clazz
* @return
*/
@RequestMapping("/mapLoad")
public Map mapLoad(HttpServletRequest req, Clazz clazz){
if(clazz.getCid() != null){
List<Map> lst = this.clazzBiz.listMapPager(clazz, null);
return lst.get(0);
}
return null;
}
@RequestMapping("/all")
public Map all(HttpServletRequest req, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
Map map = new HashMap();
map.put("lst",lst);
map.put("pageBean",pageBean);
return map;
}
@RequestMapping("/jsonStr")
public String jsonStr(HttpServletRequest req, Clazz clazz){
return "Edit";
}
}
servic层 :
public List<Map> mapListPager(Clazz clazz,PageBean pageBean) {
return clazzMapper.mapListPager(clazz);
}
mapper.xml
<select id="mapListPager" parameterType="com.zlp.ssm.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>
ClazzBizImpl
package com.zlp.ssm.biz.impl;
import com.zlp.ssm.biz.ClazzBiz;
import com.zlp.ssm.mapper.ClazzMapper;
import com.zlp.ssm.model.Clazz;
import com.zlp.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class ClazzBizImpl implements ClazzBiz {
@Autowired
private ClazzMapper clazzMapper;
@Override
public int deleteByPrimaryKey(Integer cid) {
return clazzMapper.deleteByPrimaryKey(cid);
}
@Override
public int insert(Clazz record) {
return clazzMapper.insert(record);
}
@Override
public int insertSelective(Clazz record) {
return clazzMapper.insertSelective(record);
}
@Override
public Clazz selectByPrimaryKey(Integer cid) {
return clazzMapper.selectByPrimaryKey(cid);
}
@Override
public int updateByPrimaryKeySelective(Clazz record) {
return clazzMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Clazz record) {
return clazzMapper.updateByPrimaryKey(record);
}
@Override
public List<Clazz> listPager(Clazz clazz, PageBean pageBean) {
return clazzMapper.listPager(clazz);
}
@Override
public List<Map> listMapPager(Clazz clazz, PageBean pageBean) {
return clazzMapper.listMapPager(clazz);
}
}
<%--
Created by IntelliJ IDEA.
User: zjjt
Date: 2022/8/22
Time: 18:39
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/mapList">返回list<Map>对象</a><hr>
<a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回T对象</a><hr>
<a href="${pageContext.request.contextPath}/clz/json/mapLoad?cid=1">返回Map对象</a><hr>
<a href="${pageContext.request.contextPath}/clz/json/all">返回混合对象</a><hr>
</body>
</html>
package com.zlp.ssm.web;
import com.zlp.ssm.biz.ClazzBiz;
import com.zlp.ssm.model.Clazz;
import com.zlp.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;
@Controller
@RequestMapping("/clz/json")
public class JsonController {
@Autowired
private ClazzBiz clazzBiz;
@ResponseBody
@RequestMapping("/clzEdit")
public String clzEdit(){
System.out.println("JsonController.list");
return "clzEdit";
}
// list<T>
@ResponseBody
@RequestMapping("/list")
public List<Clazz> list(HttpServletRequest request,Clazz clazz){
// System.out.println("JsonController.list");
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){
// System.out.println("JsonController.list");
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
// [{},{}]
return
this.clazzBiz.listMapPager(clazz,pageBean);
}
// Map
@ResponseBody
@RequestMapping("/map")
public Map map(HttpServletRequest request, Clazz clazz){
// System.out.println("JsonController.list");
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
// System.out.println("JsonController.list");
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
// {}
return this.clazzBiz.listPager(clazz,pageBean).get(0);
}
// {
// msg:"",
// code:200,
// data:[],
// pageBean:{}
// }
@ResponseBody
@RequestMapping("/hunhe")
public Map hunhe(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);
}
}
list
返回t对象
返回map对象
返回混合对象
三、SpringMVC 的全局异常处理
1、SpringMVC自带的简单异常处理器
SpringMVC的配置文件
<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义默认的异常处理页面 -->
<property name="defaultErrorView" value="error"/>
<!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
<property name="exceptionAttribute" value="ex"/>
<!-- 定义需要特殊处理的异常,这是重要点 -->
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop>
</props>
<!-- 还可以定义其他的自定义异常 -->
</property>
</bean>
返回list对象
2、通过HandlerExceptionResovler接口实现全局异常
GlobalException
package com.zlp.ssm.exception;
/**
* @author zlp
* @create 2022-08-22 19:11
*/
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);
}
}
GlobalExceptionHandler
package com.zlp.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 zlp
* @create 2022-08-22 19:15
*/
@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;
}
}
controller层
// T
@ResponseBody
@RequestMapping("/load")
public Clazz load(HttpServletRequest request, Clazz clazz){
// http://localhost:8080/clz/json/load?cid=2
// System.out.println("JsonController.list");
// PageBean pageBean=new PageBean();
// pageBean.setRequest(request);
// {}
if(clazz.getCid()!=null){
List<Clazz> lst=this.clazzBiz.listPager(clazz,null);
if(true)
throw new GlobalException("错误出现在JsonController.load");
return lst.get(0);
}
return null;
}
3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
GlobalExceptionResolver
package com.zlp.ssm.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* @author zlp
* @create 2022-08-22 20:10
*/
@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;
}
}
4、全局异常处理JSON返回
GlobalExceptionJsonResolver:
package com.zlp.ssm.exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
/**
* @author zlp
* @create 2022-08-22 20:19
*/
@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;
}
}
点击返回对象