liuxiaolong
2019-05-06 a7bed6b4cfecd61ec153818945f982c5bb796b98
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.cloud.common.utils;
 
import java.util.Map;
 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.util.CollectionUtils;
 
/**
 * 分页参数处理工具
 * 
 * @author bsk
 *
 */
@Slf4j
public class PageUtil {
 
    /**
     * 分页参数,起始位置,从0开始
     */
    public static final String START = "start";
    /**
     * 分页参数,每页数据条数
     */
    public static final String LENGTH = "length";
 
    /**
     * 转换并校验分页参数<br>
     * mybatis中limit #{start, JdbcType=INTEGER}, #{length,
     * JdbcType=INTEGER}里的类型转换貌似失效<br>
     * 我们这里先把他转成Integer的类型
     *
     * @param params
     * @param required
     *            分页参数是否是必填
     */
    public static void pageParamConver(Map<String, Object> params, boolean required) {
        if (required) {
            // 分页参数必填时,校验参数
            if (params == null || !params.containsKey(START) || !params.containsKey(LENGTH)) {
                throw new IllegalArgumentException("请检查分页参数," + START + "," + LENGTH);
            }
        }
 
        if (!CollectionUtils.isEmpty(params)) {
            if (params.containsKey(START)) {
                Integer start = MapUtils.getInteger(params, START);
                if (start < 0) {
                    log.error("start:{},重置为0", start);
                    start = 0;
                }
                params.put(START, start);
            }
 
            if (params.containsKey(LENGTH)) {
                Integer length = MapUtils.getInteger(params, LENGTH);
                if (length < 0) {
                    log.error("length:{},重置为0", length);
                    length = 0;
                }
                params.put(LENGTH, length);
            }
        }
    }
}