JSON返回值:
1.返回List
2.返回List
实现步骤
SpringMVC框架如何产生上述三种格式的数据
1.导入pom依赖 (Jackson)
2.配置SpringMVC.xml 配置适配器(作用是做json数据转换的)
3.使用注解==@responseBoby==能够将任何数据转换为Json对象
4.前端代码测试
导入pom依赖
<!--用来springMvc接收JSON格式转换-->
<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-servlet.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>
在创建controller类加入注解==@Controller== 和 @ResponseBody,这里我们可以加入一个窄路径,以便于我们后期区分==@RequestMapping(“/clz/json”)==
JsonController
package com.xlb.ssm.controller;
import com.xlb.ssm.biz.ClazzBiz;
import com.xlb.ssm.model.Clazz;
import com.xlb.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 波哥
* @QQ 2212371722
* @company 波哥集团
* @create 2022-08-22 16:27
*/
@Controller
@ResponseBody
@RequestMapping("/clz/json")
public class JsonController {
@Autowired
private ClazzBiz clazzBiz;
/*
* 加入了ResponseBody注解,那么就会绕过视图解析器,就会把返回值认作为是一个字符串
*/
@RequestMapping("/clzEdit")
public String clzEdit(){
System.out.println("JsonController.clzEdit");
return "clzEdit";
}
/**
* 查询全部
* @param request
* @param clazz
* @return 返回一个[{},{}]形式的JSON数组
*/
@RequestMapping("/list")
public List<Clazz> list(HttpServletRequest request,Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return this.clazzBiz.listPager(clazz,pageBean);
}
/**
*
* @param request
* @param clazz
* @return 返回List
@RequestMapping("/listMap")
public List<Map> listMap(HttpServletRequest request, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return this.clazzBiz.listMapPager(clazz,pageBean);
}
/**
* 传入cid,就会只查出一种格式
* @param request
* @param clazz
* @return 返回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);
}
/**
*
* @param request
* @param clazz
* @return 返回T对象
*/
@RequestMapping("/load")
public Clazz load(HttpServletRequest request, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return this.clazzBiz.listPager(clazz,pageBean).get(0);
}
/**
*
* @param request
* @param clazz
* @return 返回混合对象
*/
@RequestMapping("/hunhe")
public Map hunhe(HttpServletRequest request, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
List<Clazz> clazzes = this.clazzBiz.listPager(clazz, pageBean);
Map map = new HashMap();
map.put("data",clazzes);
map.put("pagebean",pageBean);
return map;
}
}
前端测试代码
index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/19
Time: 20:32
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>
测试结果
测试返回List对象
返回List≶Map>对象
返回T对象
在我们的配置文件加入此代码
<!-- 统一异常处理 -->
<!-- springmvc提供的简单异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义默认的异常处理页面 -->
<property name="defaultErrorView" value="error"/>
<!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
<property name="exceptionAttribute" value="ex"/>
<!-- 定义需要特殊处理的异常,这是重要点 -->
<property name="exceptionMappings">
<props>
<!--key代表出现什么异常就跳转到指定的页面-->
<prop key="java.lang.RuntimeException">error</prop>
</props>
<!-- 还可以定义其他的自定义异常 -->
</property>
</bean>
因为我们上面定义了一个错误java.lang.RuntimeException,跳转的界面error.jsp,而且返回值是ex
所有我们建立一个error.jsp页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/22
Time: 18:06
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>
在定义RuntimeException的错误
JsonController
package com.xlb.ssm.controller;
import com.xlb.ssm.biz.ClazzBiz;
import com.xlb.ssm.exception.GlobalException;
import com.xlb.ssm.model.Clazz;
import com.xlb.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 org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 波哥
* @QQ 2212371722
* @company 波哥集团
* @create 2022-08-22 16:27
*
* @Controller+@ResponseBody=@RestController
*/
@RestController
@RequestMapping("/clz/json")
public class JsonController {
@Autowired
private ClazzBiz clazzBiz;
/*
* 加入了ResponseBody注解,那么就会绕过视图解析器,就会把返回值认作为是一个字符串
*/
@RequestMapping("/clzEdit")
public String clzEdit(){
System.out.println("JsonController.clzEdit");
return "clzEdit";
}
/**
* 查询全部
* @param request
* @param clazz
* @return 返回一个[{},{}]形式的JSON数组
*/
@RequestMapping("/list")
public List<Clazz> list(HttpServletRequest request,Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
if(true){
throw new RuntimeException("查询班级错误出现在 JsonController.list");
}
return this.clazzBiz.listPager(clazz,pageBean);
}
/**
*
* @param request
* @param clazz
* @return 返回List
@RequestMapping("/listMap")
public List<Map> listMap(HttpServletRequest request, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return this.clazzBiz.listMapPager(clazz,pageBean);
}
/**
* 传入cid,就会只查出一种格式
* @param request
* @param clazz
* @return 返回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);
}
/**
*
* @param request
* @param clazz
* @return 返回T对象
*/
@RequestMapping("/load")
public Clazz load(HttpServletRequest request, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
return this.clazzBiz.listPager(clazz,pageBean).get(0);
}
/**
*
* @param request
* @param clazz
* @return 返回混合对象
*/
@RequestMapping("/hunhe")
public Map hunhe(HttpServletRequest request, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
List<Clazz> clazzes = this.clazzBiz.listPager(clazz, pageBean);
Map map = new HashMap();
map.put("data",clazzes);
map.put("pagebean",pageBean);
return map;
}
}
ClazzBizImpl中定义
@Override
public List<Map> listMapPager(Clazz clazz, PageBean pageBean) {
if(true){
throw new RuntimeException("查询班级异常,异常存在业务层ClazzBizImpl.listMapPager ");
}
return clazzMapper.listMapPager(clazz);
}
测试返回T对象
测试返回Map对象
测试 返回List≶Map>对象
这里要注意,假如我们前面有进行SpringMvc错误,那么我们要先将上面SpringMVC中关于异常处理的配置取消掉
首先创建GlobalException类继承 RuntimeException 再添加其构造方法
package com.xlb.ssm.exception;
/**
* @author 波哥
* @QQ 2212371722
* @company 波哥集团
* @create 2022-08-22 18:11
*/
public class GlobalException extends RuntimeException{
//1.继承RuntimeException
//2.添加构造方法
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。
创建完类后首先我们实现HandlerExceptionResolver接口,实现方resolveException,在添加注解(@Component)交给Spring管理
GlobalExceptionHandler
package com.xlb.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 波哥
* @QQ 2212371722
* @company 波哥集团
* @create 2022-08-22 18:13
*
* 处理全局异常的解析器
*/
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
//1.实现HandlerExceptionResolver 接口
//2.实现方法resolveException
//3.交给Spring管理
/**
* @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",exception.getMessage());
mv.addObject("msg","全局异常,501错误代码");
}else if(e instanceof RuntimeException){
//异常为RuntimeException时
RuntimeException exception = (RuntimeException) e;
//把错误返回到页面上去
mv.addObject("ex",exception.getMessage());
mv.addObject("msg","运行时异常,601错误代码");
}
return mv;
}
}
我们在类上面加入==@ControllerAdvice注解,在创建方法public ModelAndView handler(Exception e),然后加入其注解@ExceptionHandler==
GlobalExceptionResolver
package com.xlb.ssm.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
/**
* @author 波哥
* @QQ 2212371722
* @company 波哥集团
* @create 2022-08-22 18:31
*
*/
@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",exception.getMessage());
mv.addObject("msg","全局异常GlobalExceptionResolver,501错误代码");
}else if(e instanceof RuntimeException){
//异常为RuntimeException时
RuntimeException exception = (RuntimeException) e;
//把错误返回到页面上去
mv.addObject("ex",exception.getMessage());
mv.addObject("msg","运行时异常GlobalExceptionResolver,601错误代码");
}
return mv;
}
}
因为后期我们都要进行前后端分离,所有一般我们都是后台通过JSON格式方式向前台发出响应,然后前台接收值
这里我们只需要加入注解==@RestControllerAdvice==,然后返回值改变即可,其他都跟前面一样
GlobalExceptionResolver02
package com.xlb.ssm.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
/**
* @author 波哥
* @QQ 2212371722
* @company 波哥集团
* @create 2022-08-22 18:31
*
* 当出现异常,统一向前端响应错误信息的JSON对象数据
*/
@RestControllerAdvice
public class GlobalExceptionResolver02 {
//异常处理器
@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,501错误代码");
}else if(e instanceof RuntimeException){
//异常为RuntimeException时
RuntimeException exception = (RuntimeException) e;
//把错误返回到页面上去
map.put("ex",exception.getMessage());
map.put("msg","运行时异常GlobalExceptionResolver,601错误代码");
}
return map;
}
}