欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解如何在SpringBoot項(xiàng)目中使用統(tǒng)一返回結(jié)果

 更新時(shí)間:2022年10月19日 16:23:47   作者:picacho_pkq  
在一個(gè)完整的項(xiàng)目中,如果每一個(gè)控制器的方法都返回不同的結(jié)果,那么對項(xiàng)目的維護(hù)和擴(kuò)展都會很麻煩。因此,本文為大家準(zhǔn)備了SpringBoot項(xiàng)目中使用統(tǒng)一返回結(jié)果的方法,需要的可以參考一下

在一個(gè)完整的項(xiàng)目中,如果每一個(gè)控制器的方法都返回不同的結(jié)果,那么對項(xiàng)目的維護(hù)和擴(kuò)展都會很麻煩;并且現(xiàn)在主流的開發(fā)模式時(shí)前后端分離的模式,如果后端返回各式各樣的結(jié)果,那么在前后端聯(lián)調(diào)時(shí)會非常的麻煩,還會增加前后端的格外任務(wù)。

所以,在一個(gè)項(xiàng)目中統(tǒng)一返回結(jié)果就是一個(gè)十分必要和友好的做法。接下來就用一個(gè)簡單的demo來看看統(tǒng)一返回結(jié)果的效果。

1.創(chuàng)建Spring Boot項(xiàng)目

這里比較簡單,就不詳細(xì)介紹了;將多余的文件刪除,保持項(xiàng)目的整潔;引入必要的依賴。

demo的項(xiàng)目結(jié)構(gòu)

        <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>

2.返回結(jié)果的封裝

在common包下創(chuàng)建Result結(jié)果類,將需要返回的必要數(shù)據(jù)封裝在Result結(jié)果類中;這里封裝三個(gè)屬性,第一個(gè)是返回的狀態(tài)碼,第二個(gè)是返回的描述信息,第三個(gè)是返回的數(shù)據(jù),此數(shù)據(jù)是前端需要接收展示的數(shù)據(jù)。

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;
    }

    // 服務(wù)器處理失敗
    public Result failure(){
        return new Result(Constants.RESULT_CODE_SERVER_ERROR, "服務(wù)器錯(cuò)誤");
    }

}

創(chuàng)建Constants類,規(guī)定基本的狀態(tài)碼所代表的含義;這些狀態(tài)碼的基本規(guī)定需要符合常見的狀態(tài)碼含義,并且在一個(gè)項(xiàng)目能夠保證統(tǒng)一即可。

Constants.java

public class Constants {

    public static final int RESULT_CODE_SUCCESS = 200;  // 成功處理請求
    public static final int RESULT_CODE_BAD_REQUEST = 412;  // 請求錯(cuò)誤
    public static final int RESULT_CODE_NOT_LOGIN = 402;  // 未登錄
    public static final int RESULT_CODE_PARAM_ERROR = 406;  // 傳參錯(cuò)誤
    public static final int RESULT_CODE_SERVER_ERROR= 500;  // 服務(wù)器錯(cuò)誤

    // 等等,可以根據(jù)場景繼續(xù)添加
}

最后創(chuàng)建結(jié)果類生成器ResultGenerator類,用于生成結(jié)果類。

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;
    }
}

3.后端接口實(shí)現(xiàn)

這里實(shí)現(xiàn)簡單的增刪改查,并且應(yīng)用統(tǒng)一返回結(jié)果。

3.1 創(chuàng)建實(shí)體類

User.java

@Setter
@Getter
@Generated
@ToString
public class User {
    private Integer id;
    private String name;
    private String password;
}

3.2 創(chuàng)建dao層

UserDao.java

public interface UserDao {


    /**
     * 查詢所有的用戶
     * @return
     */
    public List<User> findAllUsers();

    /**
     * 根據(jù)主鍵查詢用戶
     * @param id
     * @return
     */
    public User getUserById(Integer id);

    /**
     * 添加一個(gè)用戶
     * @param user
     * @return
     */
    public int insertUser(User user);

    /**
     * 修改一個(gè)用戶信息
     * @param user
     * @return
     */
    public int updateUser(User user);

    /**
     * 刪除一個(gè)用戶
     * @param id
     * @return
     */
    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>

3.3 創(chuàng)建Controller層

這里基本沒有任何業(yè)務(wù)邏輯可言,只是單純的增刪改查,所以也就不太需要業(yè)務(wù)層了。

UserController.java

@Controller
public class UserController {

    @Autowired
    UserDao userDao;


    /**
     * 查詢所有用戶
     * @return
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<User>> queryAll(){
        List<User> users = userDao.findAllUsers();
        return ResultGenerator.genSuccessResult(users);
    }

    /**
     * 查詢一個(gè)用戶
     * @param id
     * @return
     */
    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result<User> queryOne(@PathVariable("id") Integer id){
        if(id == null || id < 1){
            return ResultGenerator.genFailResult("缺少參數(shù)");
        }
        User user = userDao.getUserById(id);
        if(user == null){
            return ResultGenerator.genFailResult("無此數(shù)據(jù)");
        }
        return  ResultGenerator.genSuccessResult(user);
    }


    /**
     * 添加一個(gè)用戶
     * @param user
     * @return
     */
    @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("缺少參數(shù)");
        }
        return ResultGenerator.genSuccessResult(userDao.insertUser(user) > 0);
    }

    /**
     * 修改用戶信息
     * @param user
     * @return
     */
    @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("缺少參數(shù)");
        }
        User tempUser = userDao.getUserById(user.getId());
        if(tempUser == null){
            return ResultGenerator.genFailResult("參數(shù)異常");
        }
        tempUser.setName(user.getName());
        tempUser.setPassword(user.getPassword());
        return ResultGenerator.genSuccessResult(userDao.updateUser(tempUser) > 0);
    }

    /**
     * 刪除一個(gè)用戶
     * @param id
     * @return
     */
    @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public Result<Boolean> delete(@PathVariable("id") Integer id){
        if(id == null || id < 1){
            return ResultGenerator.genFailResult("缺少參數(shù)");
        }
        return ResultGenerator.genSuccessResult(userDao.deleteUser(id) > 0);
    }
 }

4.前端部分

這里前端使用ajax來與后端進(jìn)行交互,所以前端資源只需要引入jquery即可。

<script src="https://cdn.staticfile.org/jquery/1.12.0/jquery.min.js"></script>

user-test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>統(tǒng)一返回結(jié)果 | 請求測試</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">查詢接口返回?cái)?shù)據(jù)如下:</h6>
                            <p class="card-text" id="result0"></p>
                            <a href="#" class="btn btn-primary" onclick="requestQuery()">發(fā)送詳情查詢請求</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">查詢接口返回?cái)?shù)據(jù)如下:</h6>
                            <p class="card-text" id="result1"></p>
                            <a href="#" class="btn btn-primary" onclick="requestQueryList()">發(fā)送列表查詢請求</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">添加接口返回?cái)?shù)據(jù)如下:</h6>
                            <p class="card-text" id="result2"></p>
                            <a href="#" class="btn btn-primary" onclick="requestAdd()">發(fā)送添加請求</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">修改接口返回?cái)?shù)據(jù)如下:</h6>
                            <p class="card-text" id="result3"></p>
                            <a href="#" class="btn btn-primary" onclick="requestUpdate()">發(fā)送修改請求</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">刪除接口返回?cái)?shù)據(jù)如下:</h6>
                            <p class="card-text" id="result4"></p>
                            <a href="#" class="btn btn-primary" onclick="requestDelete()">發(fā)送刪除請求</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",//預(yù)期服務(wù)器返回的數(shù)據(jù)類型
            url: "/users/" + id,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                $("#result0").html(JSON.stringify(result));
            },
            error: function () {
                $("#result0").html("接口異常,請聯(lián)系管理員!");
            }
        });
    }

    function requestQueryList() {
        $.ajax({
            type: "GET",//方法類型
            dataType: "json",//預(yù)期服務(wù)器返回的數(shù)據(jù)類型
            url: "/users",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                $("#result1").html(JSON.stringify(result));
            },
            error: function () {
                $("#result1").html("接口異常,請聯(lián)系管理員!");
            }
        });
    }

    function requestAdd() {
        var name = $("#addName").val();
        var password = $("#addPassword").val();
        var data = {"name": name, "password": password}
        $.ajax({
            type: "POST",//方法類型
            dataType: "json",//預(yù)期服務(wù)器返回的數(shù)據(jù)類型
            url: "/users",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            success: function (result) {
                $("#result2").html(JSON.stringify(result));
            },
            error: function () {
                $("#result2").html("接口異常,請聯(lián)系管理員!");
            }
        });
    }

    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",//預(yù)期服務(wù)器返回的數(shù)據(jù)類型
            url: "/users",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            success: function (result) {
                $("#result3").html(JSON.stringify(result));
            },
            error: function () {
                $("#result3").html("接口異常,請聯(lián)系管理員!");
            }
        });
    }

    function requestDelete() {
        var id = $("#deleteId").val();
        if (typeof id == "undefined" || id == null || id == "" || id < 0) {
            return false;
        }
        $.ajax({
            type: "DELETE",//方法類型
            dataType: "json",//預(yù)期服務(wù)器返回的數(shù)據(jù)類型
            url: "/users/" + id,
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                $("#result4").html(JSON.stringify(result));
            },
            error: function () {
                $("#result4").html("接口異常,請聯(lián)系管理員!");
            }
        });
    }
</script>
</body>
</html>

5.驗(yàn)證

驗(yàn)證添加效果

驗(yàn)證查詢

驗(yàn)證查詢多個(gè)用戶

修改用戶

刪除用戶

測試也基本成功了,這樣統(tǒng)一的返回結(jié)果在前端接收處理數(shù)據(jù)時(shí),會十分具有優(yōu)勢,所以在完整的項(xiàng)目中也都是采用這種方案,到這里這個(gè)demo也就基本結(jié)束了。

以上就是詳解如何在SpringBoot項(xiàng)目中使用統(tǒng)一返回結(jié)果的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot使用統(tǒng)一返回結(jié)果的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java在pdf中生成表格的方法

    java在pdf中生成表格的方法

    這篇文章主要介紹了java在pdf中生成表格的方法,需要的朋友可以參考下
    2015-11-11
  • Redis內(nèi)存數(shù)據(jù)庫示例分析

    Redis內(nèi)存數(shù)據(jù)庫示例分析

    Redis本身的內(nèi)容比較復(fù)雜。如果你上來,你應(yīng)該研究一個(gè)細(xì)節(jié)點(diǎn),比如連接池和數(shù)據(jù)結(jié)構(gòu)。雖然可以直接了解某一點(diǎn)的詳細(xì)來源內(nèi)容,甚至盡快解決一些意外,但是容易淹沒在失眠的細(xì)節(jié)中,整體控制不了Redis
    2022-12-12
  • Java String字符串內(nèi)容實(shí)現(xiàn)添加雙引號

    Java String字符串內(nèi)容實(shí)現(xiàn)添加雙引號

    這篇文章主要介紹了Java String字符串內(nèi)容實(shí)現(xiàn)添加雙引號,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • springboot整合token的實(shí)現(xiàn)代碼

    springboot整合token的實(shí)現(xiàn)代碼

    這篇文章主要介紹了springboot整合token的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Java出現(xiàn)中文亂碼問題分析及解決方案

    Java出現(xiàn)中文亂碼問題分析及解決方案

    在Java開發(fā)中,處理中文亂碼是一個(gè)常見的問題,由于字符集和編碼的復(fù)雜性,開發(fā)者可能面臨各種導(dǎo)致亂碼的情況,正確地處理中文字符集對于確保應(yīng)用程序的可靠性和國際化至關(guān)重要,本文給大家介紹了Java中文亂碼分析及解決方案,需要的朋友可以參考下
    2024-02-02
  • Mybatis中typeAliases標(biāo)簽和package標(biāo)簽使用

    Mybatis中typeAliases標(biāo)簽和package標(biāo)簽使用

    這篇文章主要介紹了Mybatis中typeAliases標(biāo)簽和package標(biāo)簽使用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java的Spring框架中bean的繼承與內(nèi)部bean的注入

    Java的Spring框架中bean的繼承與內(nèi)部bean的注入

    這篇文章主要介紹了Java的Spring框架中bean的繼承與內(nèi)部bean的注入,Spring框架是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下
    2015-12-12
  • 帶你深入理解MyBatis緩存機(jī)制

    帶你深入理解MyBatis緩存機(jī)制

    緩存是一般的ORM框架都會提供的功能,目的就是提升查詢的效率和減少數(shù)據(jù)庫的壓力,跟Hibernate 一樣,MyBatis 也有一級緩存和二級緩存,并且預(yù)留了集成第三方緩存的接口,這篇文章主要給大家介紹了關(guān)于MyBatis緩存機(jī)制的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • SpringCloud如何實(shí)現(xiàn)Zuul集群(負(fù)載均衡)

    SpringCloud如何實(shí)現(xiàn)Zuul集群(負(fù)載均衡)

    這篇文章主要介紹了SpringCloud如何實(shí)現(xiàn)Zuul集群(負(fù)載均衡)的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java常用排序算法及性能測試集合

    Java常用排序算法及性能測試集合

    周末天氣不好,在家無事,把常用排序算法理了一遍,收獲不小,特寫文章紀(jì)念。這些算法在學(xué)校的時(shí)候?qū)W過一遍,很多原理都忘記了
    2013-06-06

最新評論