目录
2、通过HandlerExceptionResovler接口实现全局异常
3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
一、SpringMVC对JSON的支持
1、josn的形式
{}->json对象
[]->json数组
{
msg:"",
code:200,
data:[]
}->json混合对象
2、SpringMVC框架如何生产上述三种格式的数据
1.导入pom依赖 Jackson
2.配置SpringMVC.xml 配置适配器
作用是做json数据转换的
3.使用注解@responseBody 能够将任何的数据转成json对象
3、导入pom依赖
<!-- 用来springmvc支持josn数据转换-->
<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>
4、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">
<!--处理中文乱码以及避免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>
5、后台代码
ClazzBiz
package com.zking.ssm.biz;
import com.zking.ssm.model.Clazz;
import com.zking.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<Clazz> listPager(Clazz clazz, PageBean pageBean);
List<Map> listMapPager(Clazz clazz, PageBean pageBean);
}
ClazzBizImpl
package com.zking.ssm.impl;
import com.zking.ssm.biz.ClazzBiz;
import com.zking.ssm.mapper.ClazzMapper;
import com.zking.ssm.model.Clazz;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author 白未
* @site 3185579318
* @company xxx公司
* @create 2022-08-18 23:34
*/
@Service
public class ClassBizImpl implements ClazzBiz {
@Autowired
private ClazzMapper clazzMapper;
@Override
public int deleteByPrimaryKey(Integer cid) {
return clazzMapper.deleteByPrimaryKey(cid);
}
@Override
public int insert(Clazz record) {
return clazzMapper.insertSelective(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);
}
}
ClazzMapper.java
package com.zking.ssm.mapper;
import com.zking.ssm.model.Clazz;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface ClazzMapper {
int deleteByPrimaryKey(Integer cid);
int insert(Clazz record);
int insertSelective(Clazz record);
Clazz selectByPrimaryKey(Integer cid);
List<Clazz> listPager(Clazz clazz);
List<Map> listMapPager(Clazz clazz);
int updateByPrimaryKeySelective(Clazz record);
int updateByPrimaryKey(Clazz record);
}
ClazzMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zking.ssm.mapper.ClazzMapper" >
<resultMap id="BaseResultMap" type="com.zking.ssm.model.Clazz" >
<constructor >
<idArg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="cname" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="cteacher" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="pic" jdbcType="VARCHAR" javaType="java.lang.String" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
cid, cname, cteacher, pic
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_struts_class
where cid = #{cid,jdbcType=INTEGER}
</select>
<select id="listPager" resultType="com.zking.ssm.model.Clazz" parameterType="com.zking.ssm.model.Clazz" >
select
<include refid="Base_Column_List" />
from t_struts_class
<where>
<if test="cname !=null and cname !='' ">
and cname like CONCAT('%','#{cname}','%')
</if>
<if test="cid !=null and cid !='' ">
and cname = #{cid}
</if>
</where>
</select>
<select id="listMapPager" resultType="java.util.Map" parameterType="com.zking.ssm.model.Clazz" >
select
<include refid="Base_Column_List" />
from t_struts_class
<where>
<if test="cname != null and cname != ''">
and cname like concat('%',#{cname},'%')
</if>
<if test="cid != null and cid != ''">
and cid = #{cid}
</if>
</where>
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_struts_class
where cid = #{cid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.zking.ssm.model.Clazz" >
insert into t_struts_class (cid, cname, cteacher,
pic)
values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
#{pic,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.zking.ssm.model.Clazz" >
insert into t_struts_class
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="cid != null" >
cid,
</if>
<if test="cname != null" >
cname,
</if>
<if test="cteacher != null" >
cteacher,
</if>
<if test="pic != null" >
pic,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="cid != null" >
#{cid,jdbcType=INTEGER},
</if>
<if test="cname != null" >
#{cname,jdbcType=VARCHAR},
</if>
<if test="cteacher != null" >
#{cteacher,jdbcType=VARCHAR},
</if>
<if test="pic != null" >
#{pic,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.zking.ssm.model.Clazz" >
update t_struts_class
<set >
<if test="cname != null" >
cname = #{cname,jdbcType=VARCHAR},
</if>
<if test="cteacher != null" >
cteacher = #{cteacher,jdbcType=VARCHAR},
</if>
<if test="pic != null" >
pic = #{pic,jdbcType=VARCHAR},
</if>
</set>
where cid = #{cid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.zking.ssm.model.Clazz" >
update t_struts_class
set cname = #{cname,jdbcType=VARCHAR},
cteacher = #{cteacher,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR}
where cid = #{cid,jdbcType=INTEGER}
</update>
</mapper>
JsonController
package com.zking.ssm.controller;
import com.zking.ssm.biz.ClazzBiz;
import com.zking.ssm.model.Clazz;
import com.zking.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 白未
* @site 3185579318
* @company xxx公司
* @create 2022-08-22 16:56
*/
@Controller
@RequestMapping("/clz/json")
public class JsonController {
@Autowired
private ClazzBiz clazzBiz;
@ResponseBody
@RequestMapping("/clzEdit")
public String clzEdit(){
System.out.println("JsonController.clzEdit");
return "clzEdit";
}
//List<T>
@ResponseBody
@RequestMapping("/list")
public List<Clazz> list(HttpServletRequest request,Clazz clazz){
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){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
// [{},{}]
return this.clazzBiz.listMapPager(clazz,pageBean);
}
// Map
@ResponseBody
@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
@ResponseBody
@RequestMapping("/load")
public Map load(HttpServletRequest request, Clazz clazz){
// http//localhost:8080/clz/json/load?cid=2
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
// {}
return this.clazzBiz.listMapPager(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;
}
}
6、前台代码
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/23
Time: 19:45
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/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>
7、运行
list<T>
list<Map>
T
Map
混合
8、优化:
@ResponseBody+@Controller=@restController
二、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>
error.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/23
Time: 21:22
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<T>
list<Map>
2、通过HandlerExceptionResovler接口实现全局异常
先将上面SpringMVC中关于异常处理的配置取消掉
GlobalException.java
package com.zking.ssm.exception;
/**
* @author 白未
* @site 3185579318
* @company xxx公司
* @create 2022-08-23 21:45
*/
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);
}
}
GlobalExceptionHandler.java
package com.zking.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 3185579318
* @company xxx公司
* @create 2022-08-23 21:48
*
* 处理全局异常的解析器
*/
@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",null);
mv.addObject("msg","全局异常,错误码520");
}else if(e instanceof GlobalException) {
GlobalException exception = (GlobalException) e;
mv.addObject("ex", null);
mv.addObject("msg", "运行时异常,错误码666");
}
return mv;
}
}
controller层
@RequestMapping("/load")
public Map load(HttpServletRequest request, Clazz clazz){
// http//localhost:8080/clz/json/load?cid=2
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
if(true)
throw new GlobalException("系统繁忙,请参考曾超sb");
// {}
return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
}
运行
3、使用@ControllerAdvice+@ExceptionHandler实现全局异常
GlobalExceptionResolver
package com.zking.ssm.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* @author 白未
* @site 3185579318
* @company xxx公司
* @create 2022-08-23 22:56
*/
@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","系统繁忙");
mv.addObject("msg","全局异常 GlobalExceptionResolver,错误码520");
}else if(e instanceof GlobalException) {
GlobalException exception = (GlobalException) e;
mv.addObject("ex", null);
mv.addObject("msg", "运行时异常 GlobalExceptionResolver,错误码666");
}
return mv;
}
}
4、json的通统一异常处理
GlobalExceptionResolver2
package com.zking.ssm.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
/**
* @author 白未
* @site 3185579318
* @company xxx公司
* @create 2022-08-23 22:56
*
* 当出现异常统一向前端响应错误信息的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,错误码520");
}else if(e instanceof RuntimeException) {
RuntimeException exception = (RuntimeException) e;
map.put("ex", exception.getMessage());
map.put("msg", "运行时异常 GlobalExceptionResolver,错误码666");
}
return map;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。