首页 > 其他分享 >第一个查询接口

第一个查询接口

时间:2023-04-24 23:00:28浏览次数:46  
标签:第一个 int 接口 查询 wht test import com public

第一个查询接口

Rest服务最先想到的就是查询接口

列表分页查询是每个玩家最常见接口。

  • controller 提供接口mapping
  • service 提供业务实现
  • VO 提供对象数据结构
  • 统一返回值
  • 分页数据结构
  • lombak使用
  • fastjson

添加json和lombak依赖

lombok有些特殊除了依赖还需要插件具体参考:

https://www.cnblogs.com/hcgk/p/16916452.html

fastjson暂时用不到

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

统一返回值

一个工程,一个项目甚至一个产品应该统一返回值。

如果每个后台都自己定义一套code,一套返回值数据结构,只能导致产品的混乱。

前后台联调无休止的争吵。

  • ResultDataVO
  • CommonUtil
package com.wht.test.mapper.vo;

import lombok.Data;

/**
 * 接口统一返回值对象
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:04:34
 */
@Data
public class ResultDataVO {
    public static final String SUCCESS_CODE = "200";

    public static final String FAILED_CODE = "500";

    private String code;

    private String message;

    private Object resultData;
}
package com.wht.test.util;

import com.wht.test.mapper.vo.ResultDataVO;

/**
 * 基础工具类
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:11:36
 */
public class CommonUtil {
    /**
     * 所有接口统一返回值
     *
     * @param code    编码
     * @param message 提示信息
     * @param data    数据
     * @return 结果
     */
    public static ResultDataVO result(String code, String message, Object data) {
        ResultDataVO resultDataVO = new ResultDataVO();
        resultDataVO.setCode(code);
        resultDataVO.setMessage(message);
        resultDataVO.setResultData(data);
        return resultDataVO;
    }
}

定义分页信息

分页的数据结构也应该统一封装,否则还是混乱

  • PageVO
  • PageResult
package com.wht.test.mapper.vo.common;

/**
 * 分页VO
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:17:52
 */
public class PageVO {
    protected int totalRows;    // 总页数

    protected int pageSize;     // 分页大小

    protected int curPage;      // 当前页

    protected int resultCode;   // 结果类型

    protected int orderBy;      // 排序

    protected int startIndex;   // 开始位置

    protected int endIndex;     // 结束位置

    protected int totalPages;   // 总页数

    public int getTotalRows() {
        return totalRows;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getCurPage() {
        return curPage < 0 ? 1 : curPage;
    }

    public void setCurPage(int curPage) {
        this.curPage = curPage;
    }

    public int getResultCode() {
        return resultCode;
    }

    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }

    public int getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(int orderBy) {
        this.orderBy = orderBy;
    }

    public int getStartIndex() {
        return (curPage - 1) * pageSize;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public int getEndIndex() {
        int leveNum = totalRows % pageSize;
        if (leveNum == 0) {
            return curPage * pageSize;
        } else {
            return (curPage - 1) * pageSize + leveNum;
        }
    }

    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }

    public int getTotalPages() {
        return this.totalRows % this.pageSize == 0 ? this.totalRows / this.pageSize : this.totalRows / this.pageSize + 1;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }
}
package com.wht.test.mapper.vo.common;

import lombok.Data;

import java.util.List;

/**
 * 分页列表VO
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:17:20
 */
@Data
public class PageResult<T> {
    private List<T> result;
    private PageVO pageVO;
}

测试对象数据结构定义

package com.wht.test.mapper.vo.common;

import lombok.Data;

/**
 * 测试对象
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:28:29
 */
@Data
public class RestTestVO {
    private int id;

    private String name;

    private String enterpriseId;
}

Get接口开发

  • RestTestController控制层定义
  • RestTestService业务层实现类实现
  • IRestTestService业务层接口定义
package com.wht.test.service;

import com.wht.test.mapper.vo.common.PageVO;
import com.wht.test.mapper.vo.common.RestTestVO;
import com.wht.test.mapper.vo.common.ResultDataVO;

/**
 * rest接口业务层解耦
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:00:34
 */
public interface IRestTestService {

    /**
     *
     * @param restTestVO
     * @param pageVO
     * @return
     */
    ResultDataVO getTestPageList(RestTestVO restTestVO, PageVO pageVO);
}
package com.wht.test.service.impl;

import com.wht.test.mapper.vo.common.PageResult;
import com.wht.test.mapper.vo.common.PageVO;
import com.wht.test.mapper.vo.common.RestTestVO;
import com.wht.test.mapper.vo.common.ResultDataVO;
import com.wht.test.service.IRestTestService;
import com.wht.test.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * rest接口业务层
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 22:01:08
 */
@Service
@Slf4j
public class RestTestService implements IRestTestService {
    @Override
    public ResultDataVO getTestPageList(RestTestVO restTestVO, PageVO pageVO) {
        // 有些项目不喜欢方法中request作为参数传递
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String userType = request.getHeader("userType");
        log.info("userType={}", userType);
        List<RestTestVO> testVOList = new ArrayList<>();
        // int rows = testDao.getTestPageListCount(restTestVO);
        int rows = 1000;
        if (rows > 0) {
            pageVO.setTotalRows(rows);
//          testVOList = testDao.getTestPageList(restTestVO,pageVO);
            for (int i = 0; i < 10; i++) {
                RestTestVO vo = new RestTestVO();
                vo.setId(i + 1);
                vo.setName("test_" + (i + 1));
                vo.setEnterpriseId(restTestVO.getEnterpriseId());
                testVOList.add(vo);
            }
            PageResult<RestTestVO> pageResult = new PageResult<>();
            pageResult.setResult(testVOList);
            pageResult.setPageVO(pageVO);
            return CommonUtil.result(ResultDataVO.SUCCESS_CODE, "查询成功", pageResult);
        }
        return null;
    }
}
package com.wht.test.controller;

import com.wht.test.mapper.vo.common.PageVO;
import com.wht.test.mapper.vo.common.RestTestVO;
import com.wht.test.mapper.vo.common.ResultDataVO;
import com.wht.test.service.IRestTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * rest接口控制层
 *
 * @Author 红尘过客
 * @DateTime 2023-04-24 21:56:52
 */
@RestController
public class RestTestController {
    @Autowired
    private IRestTestService restTestService;

    /**
     * 第一个rest分页查询接口模拟
     *
     * @param restTestVO   请求参数
     * @param enterpriseId 企业ID
     * @param pageSize     每页大小
     * @param curPage      当前页
     * @return 查询结果
     */
    @RequestMapping(value = "enterprises/{enterprise_id}/rest/test/{pageSize}/{curPage}", method = RequestMethod.GET)
    ResultDataVO getTestPageList(RestTestVO restTestVO, @PathVariable(value = "enterprise_id") String enterpriseId,
                                 @PathVariable(value = "pageSize") int pageSize, @PathVariable(value = "curPage") int curPage) {
        restTestVO.setEnterpriseId(enterpriseId);
        PageVO pageVO = new PageVO();
        pageVO.setCurPage(curPage);
        pageVO.setPageSize(pageSize);
        return restTestService.getTestPageList(restTestVO, pageVO);
    }

}

启动用谷歌浏览器插件验证下

  • 学习路径参数
  • 统一返回值
  • 分页信息封装方法
  • 预留dao层调用

请求地址:

http://localhost:8080/enterprises/alibaba/rest/test/20/1

返回值:

{
    "code": "200",
    "message": "查询成功",
    "resultData": {
        "result": [
            {
                "id": 1,
                "name": "test_1",
                "enterpriseId": "alibaba"
            },
            {
                "id": 2,
                "name": "test_2",
                "enterpriseId": "alibaba"
            },
            {
                "id": 3,
                "name": "test_3",
                "enterpriseId": "alibaba"
            },
            {
                "id": 4,
                "name": "test_4",
                "enterpriseId": "alibaba"
            },
            {
                "id": 5,
                "name": "test_5",
                "enterpriseId": "alibaba"
            },
            {
                "id": 6,
                "name": "test_6",
                "enterpriseId": "alibaba"
            },
            {
                "id": 7,
                "name": "test_7",
                "enterpriseId": "alibaba"
            },
            {
                "id": 8,
                "name": "test_8",
                "enterpriseId": "alibaba"
            },
            {
                "id": 9,
                "name": "test_9",
                "enterpriseId": "alibaba"
            },
            {
                "id": 10,
                "name": "test_10",
                "enterpriseId": "alibaba"
            }
        ],
        "pageVO": {
            "totalRows": 1000,
            "pageSize": 20,
            "curPage": 1,
            "resultCode": 0,
            "orderBy": 0,
            "startIndex": 0,
            "endIndex": 20,
            "totalPages": 50
        }
    }
}

标签:第一个,int,接口,查询,wht,test,import,com,public
From: https://www.cnblogs.com/hcgk/p/17351266.html

相关文章

  • Nordic Collegiate Programming Contest (NCPC) 2017 C 在线查询,更新
    Onehundredyearsfromnow,in2117,theInternationalCollegiateProgrammingContest(ofwhichtheNCPCisapart)hasexpandedsignificantlyanditisnowtheGalacticCollegiateProgrammingContest(GCPC).Thisyeartherearenteamsinthecontest.T......
  • API接口,用户登录,获取用户信息,用户退出
    这个是前端请求的用户相关接口。路由:routers/apiRouters.go  funcApiRouter(router*gin.Engine){//会员登录router.POST("users/login",controllers.UserLogin)//使用JWT对用户的请求进行验证user:=router.Group("users/",middleware.CheckAuth......
  • 【ⓈSpring & Spring MVC】Spring核心接口InitializingBean与SmartInitializingSingle
    SmartInitializingSingletonSmartInitializingSingleton中只有一个接口afterSingletonsInstantiated(),其作用是在spring容器管理的所有单例对象(非懒加载对象)初始化完成之后调用的回调接口。InitializingBeanInitializingBean接口为bean提供了初始化方法的方式,它只包括afterProp......
  • 调用有道翻译接口进行翻译
    1'''2i:你好3from:AUTO4to:AUTO5smartresult:dict6client:fanyideskweb7salt:16643765479061//毫秒级别的时间戳后面加上个0-9之间的随机数,js代码:r+parseInt(10*Math.random(),10);这里的r表示时间戳字符串8sign:1d69ce8f7c6258......
  • SpringSecurity从入门到精通:登录接口代码实现&测试接口
    登录接口代码实现 @RestController @RestControllerpublicclassLoginController{@AutowiredprivateLoginServcieloginServcie;@PostMapping("/user/login")publicResponseResultlogin(@RequestBodyUseruser){returnloginServ......
  • Java中Runnable和Callable的区别 Runnable接口
    Callable接口从Java1.0开始,它是java.lang包的一部分从Java1.5开始,它是java.util.concurrent包的一部分。Runnable接口不能返回计算的结果。Callable接口可以返回一个任务的并行处理的结果。Runnable接口不能抛出一个有检查的异常。Callable接口可以抛出一个有检查的异常。......
  • 第十天第一个问题
    问题描述:编写一个程序,它使用下面的函数:fill_array()将一个double数组的名称和长度作为参数。提示用户输入double值,并将这些值存储到数组中去。当数组被填满或用户输入了非数字的数据的时候结束。show_array()将一个double数组的名称和长度作为参数,并显示该数组的内容。reverse_......
  • 1 Go语言介绍、 2 Go开发环境搭建 、3 第一个helloworld 、4 变量命名规范 、5 变量的
    目录1Go语言介绍2Go开发环境搭建3第一个helloworld4变量命名规范5变量的定义和使用1Go语言介绍#Go语言介绍Go即Golang,是Google公司2009年11月正式对外公开的一门编程语言Go是【静态强类型】语言,是区别于解析型语言的编译型语言(静态:类型固定强类型:不同类型不允许直接......
  • 期刊会议名缩写查询-1
    投往IEEEtransactions的论文,其中的参考文献格式都是采用会议期刊的缩写。本博客特此记录如何查询期刊和会议名的缩写问题。期刊名缩写SCI论文的参考文献很多期刊名都是缩写,如下图所示。在写论文时,如何查询SCI期刊的缩写呢?下面介绍两种方法,一种是使用WebofScience网站查询,比......
  • API接口item_get-获取lazada商品详情(num_iid宝贝ID、title商品标题、price价格、nick
    什么是API?API是一个缩写,它代表了一个pplicationPAGC软件覆盖整个房间。API是用于构建软件应用程序的一组例程,协议和工具。API指定一个软件程序应如何与其他软件程序进行交互。例行程序:执行特定任务的程序。例程也称为过程,函数或子例程。协议:在两个系统之间传输数据的格式。......