首页 > 其他分享 >@RequestAttribute,@RequestBody 注解,代码实现分页查询

@RequestAttribute,@RequestBody 注解,代码实现分页查询

时间:2022-12-07 19:00:27浏览次数:42  
标签:interfaceId String RequestAttribute Param RequestBody toString interface 注解 id

@RequestAttribute,@RequestBody 注解,代码实现分页查询

1. @RequestAttribute注解

@RequestAttribute 获取request请求域中的数据

测试如下:

发起post请求

2、@RequestBody 注解

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);而最常用的使用请求体传参的无疑是POST请求了,所以使用@RequestBody接收数据时,一般都用POST方式进行提交。在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。

注:一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam。

注:当同时使用@RequestParam()和@RequestBody时,@RequestParam()指定的参数可以是普通元素、
       数组、集合、对象等等(即:当,@RequestBody 与@RequestParam()可以同时使用时,原SpringMVC接收
       参数的机制不变,只不过RequestBody 接收的是请求体里面的数据;而RequestParam接收的是key-value
       里面的参数,所以它会被切面进行处理从而可以用普通元素、数组、集合、对象等接收)。
       即:如果参数时放在请求体中,application/json传入后台的话,那么后台要用@RequestBody才能接收到;
             如果不是放在请求体中的话,那么后台接收前台传过来的参数时,要用@RequestParam来接收,或
             则形参前 什么也不写也能接收。

注:如果参数前写了@RequestParam(xxx),那么前端必须有对应的xxx名字才行(不管其是否有值,当然可以通
       过设置该注解的required属性来调节是否必须传),如果没有xxx名的话,那么请求会出错,报400。

注:如果参数前不写@RequestParam(xxx)的话,那么就前端可以有可以没有对应的xxx名字才行,如果有xxx名
       的话,那么就会自动匹配;没有的话,请求也能正确发送。
       追注:这里与feign消费服务时不同;feign消费服务时,如果参数前什么也不写,那么会被默认是
                  @RequestBody的。
后端@RequestBody注解对应的类在将HTTP的输入流(含请求体)装配到目标类(即:@RequestBody后面的类)时,会根据json字符串中的key来匹配对应实体类的属性,如果匹配一致且json中的该key对应的值符合(或可转换为),这一条我会在下面详细分析,其他的都可简单略过,但是本文末的核心逻辑代码以及几个结论一定要看! 实体类的对应属性的类型要求时,会调用实体类的setter方法将值赋给该属性。

json字符串中,如果value为""的话,后端对应属性如果是String类型的,那么接受到的就是"",如果是后端属性的类型是Integer、Double等类型,那么接收到的就是null。

json字符串中,如果value为null的话,后端对应收到的就是null。

如果某个参数没有value的话,在传json字符串给后端时,要么干脆就不把该字段写到json字符串中;要么写value时, 必须有值,null  或""都行。千万不能有类似"stature":,这样的写法,如:

测试如下:

查看后端:

3.mybatis 中的注解的常用方法

mapper层

package com.bcht.api.mapper;

import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

import java.util.List;
import java.util.Map;

/**
 * 接口注册
 */
@Mapper
public interface TMsOuterInterfaceMapper {
    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "listSystem")
    List<Map> listSystem(@Param("registerId") Integer registerId);

    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "listIntefaceByRegisterId")
    List<Map> listIntefaceByRegisterId(@Param("registerId") Integer registerId);

    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "listParamsByInterfaceId")
    List<Map> listParamsByInterfaceId(@Param("interfaceId") Integer interfaceId);

    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "getParamNumById")
    int getParamNumById(@Param("dirId") Integer dirId);

    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "getDetailById")
    List<Map> getDetailById(@Param("dirId") Integer dirId);

    @Results(value = {@Result(property = "interface_id", column = "interface_id", id = true, javaType = Integer.class, jdbcType = JdbcType.INTEGER)
    })
    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "getIdByCode")
    int getIdByCode(@Param("interfaceCode") String interfaceCode);

    @InsertProvider(type = TMsOuterInterfaceMapperProvider.class, method = "createInterface")
    int createInterface(@Param("interface_name") String interface_name,
                        @Param("interface_code") String interface_code,
                        @Param("register_id") Integer register_id,
                        @Param("run_status") String run_status,
                        @Param("raw_url") String raw_url,
                        @Param("req_method") String req_method,
                        @Param("desc") String desc,
                        @Param("create_user") String create_user,
                        @Param("now") String now);

    @UpdateProvider(type = TMsOuterInterfaceMapperProvider.class, method = "updateInterface")
    int updateInterface(@Param("interface_id") Integer interface_id,
                        @Param("interface_name") String interface_name,
                        @Param("interface_code") String interface_code,
                        @Param("register_id") Integer register_id,
                        @Param("run_status") String run_status,
                        @Param("raw_url") String raw_url,
                        @Param("req_method") String req_method,
                        @Param("desc") String desc,
                        @Param("update_user") String update_user,
                        @Param("now") String now);


    @UpdateProvider(type = TMsOuterInterfaceMapperProvider.class, method = "updateInterfaceStatus")
    int updateInterfaceStatus(@Param("update_user") String update_user,
                              @Param("run_status") String run_status,
                              @Param("now") String now,
                              @Param("interfaceId") Integer interfaceId);

    @UpdateProvider(type = TMsOuterInterfaceMapperProvider.class, method = "deleteInterface")
    int deleteInterface(@Param("dirId") Integer dirId);

    @DeleteProvider(type = TMsOuterInterfaceMapperProvider.class, method = "deleteParams")
    int deleteParams(@Param("interfaceId") Integer interfaceId);

    @Results(value = {@Result(property = "run_status", column = "run_status", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "checkSystemStatus")
    String checkSystemStatus(@Param("interfaceId") Integer interfaceId);

    @Results(value = {@Result(property = "interface_code", column = "interface_code", javaType = String.class, jdbcType = JdbcType.VARCHAR),
            @Result(property = "interface_name", column = "interface_name", javaType = String.class, jdbcType = JdbcType.VARCHAR)
    })
    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "checkRepeat")
    List<Map> checkRepeat(@Param("interfaceId") Integer interfaceId);


    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "queryPageResultList")
    List<Map> queryPageResultList(@Param("searchVal") String searchVal,
                                  @Param("offset") Integer offset,
                                  @Param("pageSize") Integer pageSize);

    @SelectProvider(type = TMsOuterInterfaceMapperProvider.class, method = "countResultList")
    Integer countResultList(@Param("searchVal") String searchVal,
                            @Param("offset") Integer offset,
                            @Param("pageSize") Integer pageSize);

}

对用的实现类

package com.bcht.api.mapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

public class TMsOuterInterfaceMapperProvider {

    private static final String TABLE_SYSTEM = "t_ms_outer_register";

    private static final String TABLE_INTERFACE = "t_ms_outer_interface";

    private static final String TABLE_PARAMS = "t_ms_outer_interface_params";

    public String listSystem(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" * ");
            FROM(TABLE_SYSTEM);
            Object registerId = parameter.get("registerId");
            if (registerId != null && StringUtils.isNotEmpty(registerId.toString())) {
                WHERE("register_id=#{registerId}");
            }
            WHERE(" run_status <> '0' ");

        }}.toString();
    }


    public String listIntefaceByRegisterId(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" * ");
            FROM(TABLE_INTERFACE);
            Object registerId = parameter.get("registerId");
            if (registerId != null && StringUtils.isNotEmpty(registerId.toString())) {
                WHERE("register_id=#{registerId}");
            }
            WHERE(" run_status <> '0' ");
            ORDER_BY(" update_time desc ");

        }}.toString();
    }

    public String listParamsByInterfaceId(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" * ");
            FROM(TABLE_PARAMS);
            Object interfaceId = parameter.get("interfaceId");
            if (interfaceId != null && StringUtils.isNotEmpty(interfaceId.toString())) {
                WHERE("interface_id=#{interfaceId}");
            }

        }}.toString();
    }

    public String getParamNumById(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" count(1) cnt ");
            FROM(TABLE_PARAMS);
            WHERE("interface_id=#{dirId}");
        }}.toString();
    }

    public String getDetailById(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" * ");
            FROM(TABLE_INTERFACE);
            WHERE("interface_id=#{dirId}");
            WHERE(" run_status <> '0' ");
        }}.toString();
    }


    public String getIdByCode(Map<String, Object> parameter) {
        return new SQL() {
            {
                SELECT(" interface_id ");
                FROM(TABLE_INTERFACE);
                WHERE("`interface_code`=#{interfaceCode}");
                WHERE(" run_status <> '0' ");
            }
        }.toString();
    }


    public String createInterface(Map<String, Object> parameter) {
        return new SQL() {{
            INSERT_INTO(TABLE_INTERFACE);
            VALUES("`interface_name`", "#{interface_name}");
            VALUES("`interface_code`", "#{interface_code}");
            VALUES("`register_id`", "#{register_id}");
            VALUES("`run_status`", "#{run_status}");
            VALUES("`raw_url`", "#{raw_url}");
            VALUES("`req_method`", "#{req_method}");
            VALUES("`desc`", "#{desc}");
            VALUES("`create_user`", "#{create_user}");
            VALUES("`create_time`", "#{now}");
        }}.toString();

    }


    public String updateInterface(Map<String, Object> parameter) {
        return new SQL() {{
            UPDATE(TABLE_INTERFACE);
            SET("`interface_name` = #{interface_name}");
            SET("`interface_code` = #{interface_code}");
            SET("`register_id` = #{register_id}");
            SET("`run_status` = #{run_status}");
            SET("`raw_url` = #{raw_url}");
            SET("`req_method` = #{req_method}");
            SET("`desc` = #{desc}");
            SET("`update_user` = #{update_user}");
            SET("`update_time` = #{now}");
            WHERE("`interface_id` = #{interface_id}");
        }}.toString();

    }

    public String updateInterfaceStatus(Map<String, Object> parameter) {
        return new SQL() {{
            UPDATE(TABLE_INTERFACE);
            SET("`run_status` = #{run_status}");
            SET("`update_user` = #{update_user}");
            SET("`update_time` = #{now}");
            WHERE("`interface_id` = #{interfaceId}");
        }}.toString();

    }

    public String deleteInterface(Map<String, Object> parameter) {
        return new SQL() {{
            UPDATE(TABLE_INTERFACE);
            SET("`run_status` = '0' ");
            WHERE("`interface_id`=#{dirId}");
        }}.toString();
    }

    public String deleteParams(Map<String, Object> parameter) {
        return new SQL() {{
            DELETE_FROM(TABLE_PARAMS);
            Object interfaceId = parameter.get("interfaceId");
            if (interfaceId != null && StringUtils.isNotEmpty(interfaceId.toString())) {
                WHERE(" interface_id = #{interfaceId} ");
            }
        }}.toString();
    }


    public String checkSystemStatus(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" b.run_status ");
            FROM(TABLE_INTERFACE + " a ");
            LEFT_OUTER_JOIN(TABLE_SYSTEM + " b on a.register_id = b.register_id ");
            Object interfaceId = parameter.get("interfaceId");
            if (interfaceId != null && StringUtils.isNotEmpty(interfaceId.toString())) {
                WHERE(" a.interface_id = #{interfaceId} ");
            }
        }}.toString();
    }

    public String checkRepeat(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" interface_code,interface_name ");
            FROM(TABLE_INTERFACE);
            Object interfaceId = parameter.get("interfaceId");
            if (interfaceId != null && StringUtils.isNotEmpty(interfaceId.toString())) {
                WHERE(" interface_id <> #{interfaceId} ");
            }
            WHERE(" run_status <> '0' ");
            GROUP_BY(" interface_code,interface_name ");
        }}.toString();
    }


    public String queryPageResultList(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" a.*,b.register_name ");
            FROM(TABLE_INTERFACE + " a ");
            LEFT_OUTER_JOIN(TABLE_SYSTEM + " b on a.register_id = b.register_id ");
            Object searchVal = parameter.get("searchVal");
            if (searchVal != null && StringUtils.isNotEmpty(searchVal.toString())) {
                WHERE(" a.interface_name like concat('%', '" + parameter.get("searchVal").toString() + "', '%')");
            }
            WHERE(" a.run_status <> '0' ");
            ORDER_BY(" a.update_time desc limit #{offset},#{pageSize} ");

        }}.toString();
    }

    public String countResultList(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" count(1) ");
            FROM(TABLE_INTERFACE);
            Object searchVal = parameter.get("searchVal");
            if (searchVal != null && StringUtils.isNotEmpty(searchVal.toString())) {
                WHERE("interface_name like concat('%', '" + parameter.get("searchVal").toString() + "', '%')");
            }
            WHERE(" run_status <> '0' ");
            ORDER_BY(" update_time desc limit #{offset},#{pageSize} ");
        }}.toString();
    }

}

4、通过pageNum和pageSize 实现分页查询

通过页数和每页有多少数据量,求得偏移量,然后通过 limit 偏移量,数量。求得查询的数据,然后做展示就行了、

代码如下:

Controller层:

    /**
     * 分页查询
     *
     * @param loginUser
     * @param searchVal
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/list-paging")
    public Result listPaging(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
                             @RequestParam(value = "searchVal", required = false) String searchVal,
                             @RequestParam("pageNo") Integer pageNo,
                             @RequestParam("pageSize") Integer pageSize) {
        return tMsOuterInterfaceService.queryPageList(loginUser.getId(), searchVal, pageNo, pageSize);
    }

Service层:

   /**
     * 分页查询
     *
     * @param userId
     * @param searchVal
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Result queryPageList(Integer userId, String searchVal, int pageNo, int pageSize) {
        Result result = new Result();
        Integer offset = (pageNo - 1) * pageSize;
        List<Map> list = tMsOuterInterfaceMapper.queryPageResultList(searchVal, offset, pageSize);
        if (list.size() > 0) {
            for (Map map : list) {
                String run_statusName = "";
                String req_method = "";
                String position = "";
                String type = "";
                String is_required = "";
                switch (map.get("run_status").toString()) {
                    case "0":
                        run_statusName = TABLE_RUN_DELETED.getName();
                        break;
                    case "1":
                        run_statusName = TABLE_RUN_ENABLED.getName();
                        break;
                    case "2":
                        run_statusName = TABLE_RUN_DISABLED.getName();
                        break;
                }
                switch (map.get("req_method").toString()) {
                    case "1":
                        req_method = HTTP_GET.getName();
                        break;
                    case "2":
                        req_method = HTTP_POST.getName();
                        break;
                }
                Integer interfaceId = (Integer) map.get("interface_id");
                List<Map> paramList = tMsOuterInterfaceMapper.listParamsByInterfaceId(interfaceId);
                for (Map param : paramList) {
                    switch (param.get("position").toString()) {
                        case "0":
                            position = POSITION_HEADER.getName();
                            break;
                        case "1":
                            position = POSITION_QUERY.getName();
                            break;
                        case "2":
                            position = POSITION_BODY.getName();
                            break;
                    }
                    switch (param.get("type").toString()) {
                        case "1":
                            type = TYPE_CONST.getName();
                            break;
                        case "2":
                            type = TYPE_DATE.getName();
                            break;
                    }
                    switch (param.get("is_required").toString()) {
                        case "0":
                            is_required = IS_REQUIRED_FALSE.getName();
                            break;
                        case "1":
                            is_required = IS_REQUIRED_TRUE.getName();
                            break;
                    }
                    param.put("positionName", position);
                    param.put("typeName", type);
                    param.put("is_requiredName", is_required);

                }
                map.put("param", paramList);
                map.put("run_statusName", run_statusName);
                map.put("req_methodName", req_method);
            }
        }
        result.setData(list);
        Map<String, Object> mapData = new HashMap<>();
        Integer total = tMsOuterInterfaceMapper.countResultList(searchVal, offset, pageSize);
        mapData.put("total", total);
        result.setDataMap(mapData);
        putMsg(result, Status.SUCCESS);
        return result;
    }

Mapper层:

    public String countResultList(Map<String, Object> parameter) {
        return new SQL() {{
            SELECT(" count(1) ");
            FROM(TABLE_INTERFACE);
            Object searchVal = parameter.get("searchVal");
            if (searchVal != null && StringUtils.isNotEmpty(searchVal.toString())) {
                WHERE("interface_name like concat('%', '" + parameter.get("searchVal").toString() + "', '%')");
            }
            WHERE(" run_status <> '0' ");
            ORDER_BY(" update_time desc limit #{offset},#{pageSize} ");
        }}.toString();
    }

标签:interfaceId,String,RequestAttribute,Param,RequestBody,toString,interface,注解,id
From: https://www.cnblogs.com/atao-BigData/p/16964263.html

相关文章

  • java 注解
    1.声明bean @Component 组件,没有明确的角色@Controller 在展现层使用,控制器的声明(Controller层)@Service 在业务逻辑层使用(service层)@Repository 在数据访问层使用(d......
  • Servlet_生命周期详解和Servlet_3.0注解配置
    Servlet_生命周期详解:1.被创建:执行init方法,只执行一次Servlet什么时候被创建?默认情况下,第一次被访问时,Servlet被创建可以配置执行Servlet的创建时机......
  • 多数据源配置 springboot+druid+mybatisplus使用注解整合
     1.pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"......
  • @Transactional注解事务失效的几种场景及原因
    1.介紹在业务开发的许多场景中,我们会使用到通过事务去控制多个操作的一致性。比较多的就是通过声明式事务,即使用@Transactional注解修饰方法的形式。但在使用过程中,要......
  • @RequestBody默认值注入踩坑及解决
    一、环境<properties><spring.version>5.3.22</spring.version><spring-boot.version>2.7.3</spring-boot.version><spring-cloud.version>3.1.3</......
  • 【重温SSM框架系列】10 - Spring AOP开发的两种方式(基于XML、基于注解)
    AOP开发​​概述​​​​基于XML的AOP开发​​​​1.导入AOP依赖包​​​​2.创建目标类和接口​​​​3.创建切面类(增强方法类)​​​​4.将目标类和切面类交给Spri......
  • Spring源码-04-注解Bean读取器
    Spring源码-04-注解Bean读取器AnnotatedBeanDefinitionReader一构造方法publicAnnotatedBeanDefinitionReader(BeanDefinitionRegistryregistry,Environmentenviro......
  • Spring Boot 最核心的 25 个注解
    SpringBoot最核心的25个注解1、@SpringBootApplication这是SpringBoot最最最核心的注解,用在SpringBoot主类上,标识这是一个SpringBoot应用,用来开启SpringB......
  • Spring纯注解方式使用AOP
    Aop配置类packagecom.mt.spring5.aopanno;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;......
  • Spring中@Async注解使用及配置
    Spring中@Async注解使用及配置参考文章:https://blog.csdn.net/weixin_42272869/article/details/123082657一、@Async注解的使用在使用spring框架中,可以非常简单方便的......