Table of Contents
Presentation layer and front-end data transmission protocol definition
Implementation of presentation layer and front-end data transmission protocol
Result encapsulation
Home Java javaTutorial Java SSM integrated development unified result encapsulation example analysis

Java SSM integrated development unified result encapsulation example analysis

May 03, 2023 pm 05:07 PM
java ssm

Presentation layer and front-end data transmission protocol definition

After the SSM integration and functional module development are completed, next, we will analyze what problems we need to solve based on the above cases. First of all, the first question is:

The boolean type data returned to the front end when adding, deleting or modifying at the Controller layer

Java SSM integrated development unified result encapsulation example analysis

Querying a single data returned to the front end at the Controller layer It is an object

Java SSM integrated development unified result encapsulation example analysis

Query at the Controller layer and all returned to the front end are collection objects

Java SSM integrated development unified result encapsulation example analysis

Currently we have three types The data type is returned to the front end. As the business grows, we will need to return more and more data types. For front-end developers, it is quite messy when parsing data, so for the front-end, if the background can return a unified data result, the front-end can parse in one way when parsing. Development will become easier.

So we wonder if we can unify the returned result data and how to do it. The general idea is:

  • In order to encapsulate the returned result data: create Result model class, encapsulate data into the data attribute

  • In order to encapsulate what kind of operation the returned data is and whether the operation is successful: encapsulate the operation result into the code attribute

  • In order to encapsulate the error message returned after the operation fails: encapsulate the special message into the message (msg) attribute

Java SSM integrated development unified result encapsulation example analysis

According to the analysis, we You can set up a unified data return result class

public class Result{
	private Object data;
	private Integer code;
	private String msg;
}
Copy after login

Note: The Result class name and the fields in the class are not fixed. You can increase or decrease it as needed to provide several construction methods for convenient operation.

Implementation of presentation layer and front-end data transmission protocol

Result encapsulation

For result encapsulation, we should process it in the presentation layer, so we put the result class in the controller package Of course, you can also put it in the domain package. This is possible. How to implement result encapsulation? The specific steps are:

Step 1: Create the Result class

public class Result {
    //描述统一格式中的数据
    private Object data;
    //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
    private Integer code;
    //描述统一格式中的消息,可选属性
    private String msg;
    public Result() {
    }
    //构造方法是方便对象的创建
    public Result(Integer code,Object data) {
        this.data = data;
        this.code = code;
    }
    //构造方法是方便对象的创建
    public Result(Integer code, Object data, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    @Override
    public String toString() {
        return "Result{" +
                "data=" + data +
                ", code=" + code +
                ", msg='" + msg + '\'' +
                '}';
    }
}
Copy after login

Note:

You don’t need to write the toString method, it will be converted to json format in the end. But getter and setter methods must be present!

Step 2: Define the return code Code class

//状态码
public class Code {
    public static final Integer SAVE_OK = 20011;
    public static final Integer DELETE_OK = 20021;
    public static final Integer UPDATE_OK = 20031;
    public static final Integer GET_OK = 20041;
    public static final Integer SAVE_ERR = 20010;
    public static final Integer DELETE_ERR = 20020;
    public static final Integer UPDATE_ERR = 20030;
    public static final Integer GET_ERR = 20040;
}
Copy after login

Note: The constant design in the code class is not fixed and can be increased or decreased according to needs, for example, the query is subdivided into GET_OK ,GET_ALL_OK,GET_PAGE_OK, etc.

Step 3: Modify the return value of the Controller class

//统一每一个控制器方法返回值
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败,请重试!";
        return new Result(code,book,msg);
    }
    @GetMapping
    public Result getAll() {
        List<Book> bookList = bookService.getAll();
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "" : "数据查询失败,请重试!";
        return new Result(code,bookList,msg);
    }
}
Copy after login

The bookList is compared with null here because if no results are found in all queries, a null will be returned directly instead of returning An empty list!

When checking the book based on the ID, if it is not found, it will return a null

Finally our project structure:

Java SSM integrated development unified result encapsulation example analysis

Steps 4: Start the service test

Java SSM integrated development unified result encapsulation example analysis

#Our return results can already be returned to the front end in a unified format. Based on the returned result, the front end first obtains code from it. Based on the code judgment, if it succeeds, it takes the value of the data attribute. If it fails, it takes the value of msg. Value as a reminder.

The above is the detailed content of Java SSM integrated development unified result encapsulation example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles