Python 官方文档:入门教程 => 点击学习
目录1.创建Spring Boot项目2.返回结果的封装3.后端接口实现3.1 创建实体类3.2 创建dao层3.3 创建Controller层4.前端部分5.验证在一个完整的项目中
在一个完整的项目中,如果每一个控制器的方法都返回不同的结果,那么对项目的维护和扩展都会很麻烦;并且现在主流的开发模式时前后端分离的模式,如果后端返回各式各样的结果,那么在前后端联调时会非常的麻烦,还会增加前后端的格外任务。
所以,在一个项目中统一返回结果就是一个十分必要和友好的做法。接下来就用一个简单的demo来看看统一返回结果的效果。
这里比较简单,就不详细介绍了;将多余的文件删除,保持项目的整洁;引入必要的依赖。
demo的项目结构
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-WEB</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>Mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
在common包下创建Result结果类,将需要返回的必要数据封装在Result结果类中;这里封装三个属性,第一个是返回的状态码,第二个是返回的描述信息,第三个是返回的数据,此数据是前端需要接收展示的数据。
Result.java
@Setter
@Getter
@ToString
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
private int resultCode;
private String message;
private T data;
public Result(){
}
public Result(int resultCode, String message){
this.resultCode = resultCode;
this.message = message;
}
// 服务器处理失败
public Result failure(){
return new Result(Constants.RESULT_CODE_SERVER_ERROR, "服务器错误");
}
}
创建Constants类,规定基本的状态码所代表的含义;这些状态码的基本规定需要符合常见的状态码含义,并且在一个项目能够保证统一即可。
Constants.java
public class Constants {
public static final int RESULT_CODE_SUCCESS = 200; // 成功处理请求
public static final int RESULT_CODE_BAD_REQUEST = 412; // 请求错误
public static final int RESULT_CODE_NOT_LOGIN = 402; // 未登录
public static final int RESULT_CODE_PARAM_ERROR = 406; // 传参错误
public static final int RESULT_CODE_SERVER_ERROR= 500; // 服务器错误
// 等等,可以根据场景继续添加
}
最后创建结果类生成器ResultGenerator类,用于生成结果类。
ResultGenerator.java
public class ResultGenerator {
private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";
private static final String DEFAULT_FAIL_MESSAGE = "FAIL";
public static Result genSuccessResult(){
Result result = new Result();
result.setResultCode(Constants.RESULT_CODE_SUCCESS);
result.setMessage(DEFAULT_FAIL_MESSAGE);
return result;
}
public static Result genSuccessResult(String message){
Result result = new Result();
result.setResultCode(Constants.RESULT_CODE_SUCCESS);
result.setMessage(message);
return result;
}
public static Result genSuccessResult(Object data){
Result result = new Result();
result.setResultCode(Constants.RESULT_CODE_SUCCESS);
result.setMessage(DEFAULT_SUCCESS_MESSAGE);
result.setData(data);
return result;
}
public static Result genFailResult(String message){
Result result = new Result();
result.setResultCode(Constants.RESULT_CODE_SERVER_ERROR);
if(StringUtils.isEmpty(message)){
result.setMessage(DEFAULT_FAIL_MESSAGE);
}else{
result.setMessage(message);
}
return result;
}
public static Result genNullResult(String message){
Result result = new Result();
result.setResultCode(Constants.RESULT_CODE_BAD_REQUEST);
result.setMessage(message);
return result;
}
public static Result genErrorResult(int code, String message){
Result result = new Result();
result.setResultCode(code);
result.setMessage(message);
return result;
}
}
这里实现简单的增删改查,并且应用统一返回结果。
User.java
@Setter
@Getter
@Generated
@ToString
public class User {
private Integer id;
private String name;
private String passWord;
}
UserDao.java
public interface UserDao {
public List<User> findAllUsers();
public User getUserById(Integer id);
public int insertUser(User user);
public int updateUser(User user);
public int deleteUser(Integer id);
}
userDao.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.picacho.dao.UserDao">
<resultMap type="com.picacho.entity.User" id="UserResult">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="password" column="password"/>
</resultMap>
<select id="findAllUsers" resultMap="UserResult">
select id,name,password from tb_user
order by id desc
</select>
<select id="getUserById" resultMap="UserResult">
select id,name,password from tb_user
where id = #{id}
</select>
<insert id="insertUser" parameterType="com.picacho.entity.User">
insert into tb_user(name,password)
values(#{name},#{password})
</insert>
<update id="updateUser" parameterType="com.picacho.entity.User">
update tb_user
set
name=#{name},password=#{password}
where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from tb_user where id=#{id}
</delete>
</mapper>
这里基本没有任何业务逻辑可言,只是单纯的增删改查,所以也就不太需要业务层了。
UserController.java
@Controller
public class UserController {
@Autowired
UserDao userDao;
@RequestMapping(value = "/users", method = RequestMethod.GET)
@ResponseBody
public Result<List<User>> queryAll(){
List<User> users = userDao.findAllUsers();
return ResultGenerator.genSuccessResult(users);
}
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
@ResponseBody
public Result<User> queryOne(@PathVariable("id") Integer id){
if(id == null || id < 1){
return ResultGenerator.genFailResult("缺少参数");
}
User user = userDao.getUserById(id);
if(user == null){
return ResultGenerator.genFailResult("无此数据");
}
return ResultGenerator.genSuccessResult(user);
}
@RequestMapping(value = "/users", method = RequestMethod.POST)
@ResponseBody
public Result<Boolean> insert(@RequestBody User user){
if(StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())){
return ResultGenerator.genFailResult("缺少参数");
}
return ResultGenerator.genSuccessResult(userDao.insertUser(user) > 0);
}
@RequestMapping(value = "/users", method = RequestMethod.PUT)
@ResponseBody
public Result<Boolean> update(@RequestBody User user){
if(user.getId() == null || user.getId() < 1 || StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())){
return ResultGenerator.genFailResult("缺少参数");
}
User tempUser = userDao.getUserById(user.getId());
if(tempUser == null){
return ResultGenerator.genFailResult("参数异常");
}
tempUser.setName(user.getName());
tempUser.setPassword(user.getPassword());
return ResultGenerator.genSuccessResult(userDao.updateUser(tempUser) > 0);
}
@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
@ResponseBody
public Result<Boolean> delete(@PathVariable("id") Integer id){
if(id == null || id < 1){
return ResultGenerator.genFailResult("缺少参数");
}
return ResultGenerator.genSuccessResult(userDao.deleteUser(id) > 0);
}
}
这里前端使用ajax来与后端进行交互,所以前端资源只需要引入Jquery即可。
user-test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>统一返回结果 | 请求测试</title>
</head>
<body class="hold-transition login-page">
<div style="width:720px;margin:7% auto">
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-6">
<hr>
<div class="card">
<div class="card-header">
<h5 class="m-0">详情查询接口测试</h5>
</div>
<div class="card-body">
<input id="queryId" type="number" placeholder="请输入id字段">
<h6 class="card-title">查询接口返回数据如下:</h6>
<p class="card-text" id="result0"></p>
<a href="#" class="btn btn-primary" onclick="requestQuery()">发送详情查询请求</a>
</div>
</div>
<br>
<hr>
<div class="card">
<div class="card-header">
<h5 class="m-0">列表查询接口测试</h5>
</div>
<div class="card-body">
<h6 class="card-title">查询接口返回数据如下:</h6>
<p class="card-text" id="result1"></p>
<a href="#" class="btn btn-primary" onclick="requestQueryList()">发送列表查询请求</a>
</div>
</div>
<br>
<hr>
<div class="card">
<div class="card-header">
<h5 class="m-0">添加接口测试</h5>
</div>
<div class="card-body">
<input id="addName" type="text" placeholder="请输入name字段">
<input id="addPassword" type="text" placeholder="请输入password字段">
<h6 class="card-title">添加接口返回数据如下:</h6>
<p class="card-text" id="result2"></p>
<a href="#" class="btn btn-primary" onclick="requestAdd()">发送添加请求</a>
</div>
</div>
<br>
<hr>
<div class="card">
<div class="card-header">
<h5 class="m-0">修改接口测试</h5>
</div>
<div class="card-body">
<input id="updateId" type="number" placeholder="请输入id字段">
<input id="updateName" type="text" placeholder="请输入name字段">
<input id="updatePassword" type="text" placeholder="请输入password字段">
<h6 class="card-title">修改接口返回数据如下:</h6>
<p class="card-text" id="result3"></p>
<a href="#" class="btn btn-primary" onclick="requestUpdate()">发送修改请求</a>
</div>
</div>
<br>
<hr>
<div class="card">
<div class="card-header">
<h5 class="m-0">删除接口测试</h5>
</div>
<div class="card-body">
<input id="deleteId" type="number" placeholder="请输入id字段">
<h6 class="card-title">删除接口返回数据如下:</h6>
<p class="card-text" id="result4"></p>
<a href="#" class="btn btn-primary" onclick="requestDelete()">发送删除请求</a>
</div>
</div>
<hr>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://cdn.staticfile.org/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
function requestQuery() {
var id = $("#queryId").val();
if (typeof id == "undefined" || id == null || id == "" || id < 0) {
return false;
}
$.ajax({
type: "GET",//方法类型
dataType: "JSON",//预期服务器返回的数据类型
url: "/users/" + id,
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#result0").html(JSON.stringify(result));
},
error: function () {
$("#result0").html("接口异常,请联系管理员!");
}
});
}
function requestQueryList() {
$.ajax({
type: "GET",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users",
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#result1").html(JSON.stringify(result));
},
error: function () {
$("#result1").html("接口异常,请联系管理员!");
}
});
}
function requestAdd() {
var name = $("#addName").val();
var password = $("#addPassword").val();
var data = {"name": name, "password": password}
$.ajax({
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function (result) {
$("#result2").html(JSON.stringify(result));
},
error: function () {
$("#result2").html("接口异常,请联系管理员!");
}
});
}
function requestUpdate() {
var id = $("#updateId").val();
var name = $("#updateName").val();
var password = $("#updatePassword").val();
var data = {"id": id, "name": name, "password": password}
$.ajax({
type: "PUT",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function (result) {
$("#result3").html(JSON.stringify(result));
},
error: function () {
$("#result3").html("接口异常,请联系管理员!");
}
});
}
function requestDelete() {
var id = $("#deleteId").val();
if (typeof id == "undefined" || id == null || id == "" || id < 0) {
return false;
}
$.ajax({
type: "DELETE",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users/" + id,
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#result4").html(JSON.stringify(result));
},
error: function () {
$("#result4").html("接口异常,请联系管理员!");
}
});
}
</script>
</body>
</html>
验证添加效果
验证查询
验证查询多个用户
修改用户
删除用户
测试也基本成功了,这样统一的返回结果在前端接收处理数据时,会十分具有优势,所以在完整的项目中也都是采用这种方案,到这里这个demo也就基本结束了。
以上就是详解如何在SpringBoot项目中使用统一返回结果的详细内容,更多关于SpringBoot使用统一返回结果的资料请关注编程网其它相关文章!
--结束END--
本文标题: 详解如何在SpringBoot项目中使用统一返回结果
本文链接: https://lsjlt.com/news/169721.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0