duhuizhe
2024-04-19 d13b4aa06f28d43378f3a1b456d5a89a572c000a
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package com.yqzx.common.controller;
 
import cn.hutool.core.util.ReflectUtil;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yqzx.common.domain.query.PageQuery;
import com.yqzx.common.domain.result.CommonResult;
import com.yqzx.common.domain.result.PageBean;
import com.yqzx.common.entity.BaseEntity;
import com.yqzx.common.service.impl.BaseServiceImpl;
import com.yqzx.common.util.CommonUtil;
import com.yqzx.common.util.IdGenerator;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
 
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
 
/**
 * 功能描述:基础 controller
 *
 * @author dhz
 * @date 2024-04-13 16:30
 * @Version 1.0
 **/
public class BaseController<S extends BaseServiceImpl<T, Q, R>, T extends BaseEntity, Q extends PageQuery, R extends BaseEntity> {
    private static final Logger log = LoggerFactory.getLogger(BaseController.class);
    protected S baseService;
 
    public BaseController() {
    }
 
    public BaseController(S baseService) {
        this.baseService = baseService;
    }
 
    public void setBaseService(S baseService) {
        this.baseService = baseService;
    }
 
    public S getBaseService() {
        return this.baseService;
    }
 
    protected Class<S> currentServiceClass() {
        return this.getSuperClassGenericType(this.getClass(), 0);
    }
 
    protected Class<Q> currentQueryClass() {
        return this.getSuperClassGenericType(this.getClass(), 2);
    }
 
    protected Class<T> currentEntityClass() {
        return this.getSuperClassGenericType(this.getClass(), 1);
    }
 
    protected Class<R> currentResultClass() {
        return this.getSuperClassGenericType(this.getClass(), 3);
    }
 
    @ApiOperation(value = "查询列表", notes = "查询列表")
    @GetMapping("/getList")
    public CommonResult<PageBean> getList() {
        Q query = handlerParam(currentQueryClass());
        PageHelper.startPage(query.getPageNumber(), query.getPageSize());
        if (StringUtils.isNotBlank(query.getSortName()) && StringUtils.isNotBlank(query.getSortOrder())) {
            PageHelper.orderBy(CommonUtil.camel2Underline(query.getSortName()) + " " + query.getSortOrder());
        } else {
            PageHelper.orderBy("create_time desc");
        }
        List<R> list = baseService.getList(query);
        return handlerCommonResult(new CommonResult<>(new PageBean(list)));
    }
 
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping("/add")
    public CommonResult<Integer> add() {
        T entity = handlerId(currentEntityClass(), IdGenerator.getId());
        return handlerCommonResult(new CommonResult<>(baseService.addSelective(entity)));
    }
 
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @GetMapping("/get")
    public CommonResult<T> get(Long id) {
        T be = handlerId(currentEntityClass(), id);
        return handlerCommonResult(new CommonResult<>(baseService.get(be.getId())));
    }
 
    @ApiOperation(value = "修改", notes = "修改")
    @PostMapping("/upd")
    public CommonResult<Integer> upd() {
        T entity = handlerParam(currentEntityClass());
        return handlerCommonResult(new CommonResult<>(baseService.editSelective(entity)));
    }
 
    @ApiOperation(value = "删除", notes = "删除")
    @PostMapping("/del")
    public CommonResult<Integer> del(Long id) {
        T be = handlerId(currentEntityClass(), id);
        return handlerCommonResult(new CommonResult<>(baseService.del(be.getId())));
    }
 
 
    /**
     * 获取指定位置泛型实际class
     *
     * @param clazz class
     * @param index 泛型位置
     * @return 实际class
     */
    protected Class getSuperClassGenericType(final Class<?> clazz, final int index) {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            log.warn(String.format("Warn: %s's superclass not ParameterizedType", clazz.getSimpleName()));
            return Object.class;
        } else {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            if (index < params.length && index >= 0) {
                if (!(params[index] instanceof Class)) {
                    log.warn(String.format("Warn: %s not set the actual class on superclass generic parameter", clazz.getSimpleName()));
                    return Object.class;
                } else {
                    return (Class) params[index];
                }
            } else {
                log.warn(String.format("Warn: Index: %s, Size of %s's Parameterized Type: %s .", index, clazz.getSimpleName(), params.length));
                return Object.class;
            }
        }
    }
 
    /**
     * 获取实体对象
     *
     * @param dClass class 字节
     * @param <D>    泛型
     * @return 实体对象
     */
    public <D> D getOneInstance(Class<D> dClass) {
        Assert.notNull(dClass, "class " + dClass + "can not is null");
        try {
            return dClass.newInstance();
        } catch (Exception e) {
            log.error("创建对象失败" + e.getMessage());
            throw new RuntimeException("class [" + dClass + "] make instance is error:{}" + e.getMessage());
        }
    }
 
    /*************************以下为 防漏洞方法处理****************************/
 
    /**
     * 处理请求参数结果  适用于get请求
     * 包含查询参数 、保存参数等等参数
     *
     * @param dClass 参数class
     * @param <D>    泛型
     * @return 参数
     */
    protected <D> D handlerParam(Class<D> dClass) {
        Assert.notNull(dClass, "class " + dClass + "can not is null");
        D d = CommonUtil.getObjFromReq(dClass);
        D copy = getOneInstance(dClass);
        BeanUtils.copyProperties(d, copy);
        return copy;
    }
 
    /**
     * 处理id 的漏洞异常  适用于常用get edit add 等根据id 更新方法
     *
     * @param dClass 对象信息class
     * @param id     实际值
     * @param <D>    泛型
     * @return 处理后的 对象
     */
    protected <D> D handlerId(Class<D> dClass, Long id) {
        Assert.notNull(dClass, "class " + dClass + "can not is null");
        Assert.notNull(id, "id can not is null");
        D d = getOneInstance(dClass);
        ReflectUtil.setFieldValue(d, "id", id);
        D param = getOneInstance(dClass);
        BeanUtils.copyProperties(d, param);
        return param;
    }
 
    /**
     * 处理返回结果
     *
     * @param commonResult 原始结果
     * @return 返回处理后结果
     */
    protected CommonResult handlerCommonResult(CommonResult commonResult) {
        Assert.notNull(commonResult, "commonResult can not is null");
        CommonResult copy = new CommonResult<>();
        BeanUtils.copyProperties(commonResult, copy);
        return copy;
    }
}