写在之前:在进行javaweb的学习中,有许多的类是能够直接复用的,我将一些经常用到的类总结在这里方便能够随时看看复习😄

JWT 令牌工具类

注意:在使用该类之前需要注入相关依赖

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
public class JwtUtils {

private static String signKey = "xxxxx"; //JWT的签名
private static Long expire = 43200000L; //JWT令牌有效时间,单位:ms

/**
* 生成JWT令牌
*/
public static String generateJwt(Map<String, Object> claims){
String jwt = Jwts.builder()
.addClaims(claims)
.signWith(SignatureAlgorithm.HS256, signKey)
.setExpiration(new Date(System.currentTimeMillis() + expire))
.compact();
return jwt;
}

/**
*解析JWT令牌
*/
public static Claims parseJWT(String jwt){
Claims claims = Jwts.parser()
.setSigningKey(signKey)
.parseClaimsJws(jwt)
.getBody();
return claims;
}
}

响应结果实体类

在写实体类时可以选择引入lombok依赖,使用相关注解如@Data,@AllArgsConstructor,@NoArgsConstructor可以大大简化需要写出的内容,后面的类中用到的Result都是此处的Result

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
public class Result {
Integer code;
String msg;
Object data;

public Result(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
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;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}

/*
*这里的静态方法可以根据自己的需要具体来写
*/

public static Result success(){
return new Result(200,"success",null);
}

public static Result success(Object data){
return new Result(200,"success",data);
}

public static Result error(String msg){
return new Result(0,msg,null);
}

}

Interceptor 拦截器类

使用时必须配合相应的配置类,否则无法生效

请参考配置类 拦截器的配置类

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
public class LoginInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

String url = request.getRequestURI();

if(url.contains("login")){
return true;
}

String jwt = request.getHeader("token");

if(!StringUtils.hasLength(jwt)){
Result error = Result.error("NOT_LOGIN");
String noLogin = JSONObject.toJSONString(error);
response.getWriter().write(noLogin);
return false;
}
try {
JwtUtils.parseJWT(jwt);
}catch (Exception e){
Result error = Result.error("NOT_LOGIN");
String noLogin = JSONObject.toJSONString(error);
response.getWriter().write(noLogin);
return false;
}

return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}

拦截器的配置类

为写好的拦截器进行配置,不要省略配置类注解@Configuration

拦截器类Inteceptor拦截器

1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class WebConfig implements WebMvcConfigurer {

@Autowired
private LoginInterceptor loginInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}

Filter 过滤器类

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
@WebFilter(urlPatterns = "/*")
public class Filter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
javax.servlet.Filter.super.init(filterConfig);
System.out.println("初始化");

}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;

String url = req.getRequestURL().toString();
if(url.contains("login")){
filterChain.doFilter(servletRequest,servletResponse);
return;
}

String jwt = req.getHeader("token");

if(!StringUtils.hasLength(jwt)){
Result error = Result.error("NOT_LOGIN");
String noLogin = JSONObject.toJSONString(error);
resp.getWriter().write(noLogin);
return;
}

try {
JwtUtils.parseJWT(jwt);
}catch (Exception e){
e.printStackTrace();
Result error = Result.error("NOT_LOGIN");
String noLogin = JSONObject.toJSONString(error);
resp.getWriter().write(noLogin);
return;
}

filterChain.doFilter(servletRequest,servletResponse);

}

@Override
public void destroy() {
javax.servlet.Filter.super.destroy();
System.out.println("销毁");
}
}

全局异常处理器类

1
2
3
4
5
6
7
8
9
10
@RestControllerAdvice
public class GolableException {

@ExceptionHandler(Exception.class)
public Result handler(){

return Result.error("进行了全局异常处理");
}

}

自定义异常

在写该类时可以选择引入lombok依赖,使用相关注解如@Data,@AllArgsConstructor,@NoArgsConstructor可以大大简化需要写出的内容

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
public class CustomException extends RuntimeException{
private Integer code;
private String msg;

public CustomException(Integer code, String msg) {
this.code = code;
this.msg = msg;
}

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 "CustomException{" +
"code=" + code +
", msg='" + msg + '\'' +
'}';
}
}

在全局异常处理类中添加自定义异常

全局异常处理器类

自定义异常

1
2
3
4
5
6
7
8
9
10
@ControllerAdvice
public class GlobalExceptionHandler {

@ResponseBody
@ExceptionHandler(CustomException.class)
public Result error(CustomException e){
e.printStackTrace();
return Result.error(e.getMsg());
}
}

阿里云 OSS 图片上传工具类

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
@Component
public class AliOSSUtils {

@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;

/**
* 实现上传图片到OSS
*/
public String upload(MultipartFile file) throws IOException {
// 获取上传的文件的输入流
InputStream inputStream = file.getInputStream();

// 避免文件覆盖
String originalFilename = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

//上传文件到 OSS
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, fileName, inputStream);

//文件访问路径
String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
// 关闭ossClient
ossClient.shutdown();
return url;// 把上传到oss的路径返回
}

}

RedisTemplate 配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}


}

HttpClient 工具类

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
/**
* Http工具类
*/
public class HttpClientUtil {

static final int TIMEOUT_MSEC = 5 * 1000;

/**
* 发送GET方式请求
* @param url
* @param paramMap
* @return
*/
public static String doGet(String url,Map<String,String> paramMap){
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

String result = "";
CloseableHttpResponse response = null;

try{
URIBuilder builder = new URIBuilder(url);
if(paramMap != null){
for (String key : paramMap.keySet()) {
builder.addParameter(key,paramMap.get(key));
}
}
URI uri = builder.build();

//创建GET请求
HttpGet httpGet = new HttpGet(uri);

//发送请求
response = httpClient.execute(httpGet);

//判断响应状态
if(response.getStatusLine().getStatusCode() == 200){
result = EntityUtils.toString(response.getEntity(),"UTF-8");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return result;
}

/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);

// 创建参数列表
if (paramMap != null) {
List<NameValuePair> paramList = new ArrayList();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}

httpPost.setConfig(builderRequestConfig());

// 执行http请求
response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}

/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);

if (paramMap != null) {
//构造json格式数据
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
jsonObject.put(param.getKey(),param.getValue());
}
StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
//设置请求编码
entity.setContentEncoding("utf-8");
//设置数据类型
entity.setContentType("application/json");
httpPost.setEntity(entity);
}

httpPost.setConfig(builderRequestConfig());

// 执行http请求
response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}
private static RequestConfig builderRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MSEC)
.setConnectionRequestTimeout(TIMEOUT_MSEC)
.setSocketTimeout(TIMEOUT_MSEC).build();
}

}

微信支付工具类

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
204
/**
* 微信支付工具类
*/
@Component
public class WeChatPayUtil {

//微信支付下单接口地址
public static final String JSAPI = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";

//申请退款接口地址
public static final String REFUNDS = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";

@Autowired
private WeChatProperties weChatProperties;

/**
* 获取调用微信接口的客户端工具对象
*
* @return
*/
private CloseableHttpClient getClient() {
PrivateKey merchantPrivateKey = null;
try {
//merchantPrivateKey商户API私钥,如何加载商户API私钥请看常见问题
merchantPrivateKey = PemUtil.loadPrivateKey(new FileInputStream(new File(weChatProperties.getPrivateKeyFilePath())));
//加载平台证书文件
X509Certificate x509Certificate = PemUtil.loadCertificate(new FileInputStream(new File(weChatProperties.getWeChatPayCertFilePath())));
//wechatPayCertificates微信支付平台证书列表。你也可以使用后面章节提到的“定时更新平台证书功能”,而不需要关心平台证书的来龙去脉
List<X509Certificate> wechatPayCertificates = Arrays.asList(x509Certificate);

WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
.withMerchant(weChatProperties.getMchid(), weChatProperties.getMchSerialNo(), merchantPrivateKey)
.withWechatPay(wechatPayCertificates);

// 通过WechatPayHttpClientBuilder构造的HttpClient,会自动的处理签名和验签
CloseableHttpClient httpClient = builder.build();
return httpClient;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}

/**
* 发送post方式请求
*
* @param url
* @param body
* @return
*/
private String post(String url, String body) throws Exception {
CloseableHttpClient httpClient = getClient();

HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
httpPost.addHeader("Wechatpay-Serial", weChatProperties.getMchSerialNo());
httpPost.setEntity(new StringEntity(body, "UTF-8"));

CloseableHttpResponse response = httpClient.execute(httpPost);
try {
String bodyAsString = EntityUtils.toString(response.getEntity());
return bodyAsString;
} finally {
httpClient.close();
response.close();
}
}

/**
* 发送get方式请求
*
* @param url
* @return
*/
private String get(String url) throws Exception {
CloseableHttpClient httpClient = getClient();

HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
httpGet.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
httpGet.addHeader("Wechatpay-Serial", weChatProperties.getMchSerialNo());

CloseableHttpResponse response = httpClient.execute(httpGet);
try {
String bodyAsString = EntityUtils.toString(response.getEntity());
return bodyAsString;
} finally {
httpClient.close();
response.close();
}
}

/**
* jsapi下单
*
* @param orderNum 商户订单号
* @param total 总金额
* @param description 商品描述
* @param openid 微信用户的openid
* @return
*/
private String jsapi(String orderNum, BigDecimal total, String description, String openid) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("appid", weChatProperties.getAppid());
jsonObject.put("mchid", weChatProperties.getMchid());
jsonObject.put("description", description);
jsonObject.put("out_trade_no", orderNum);
jsonObject.put("notify_url", weChatProperties.getNotifyUrl());

JSONObject amount = new JSONObject();
amount.put("total", total.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
amount.put("currency", "CNY");

jsonObject.put("amount", amount);

JSONObject payer = new JSONObject();
payer.put("openid", openid);

jsonObject.put("payer", payer);

String body = jsonObject.toJSONString();
return post(JSAPI, body);
}

/**
* 小程序支付
*
* @param orderNum 商户订单号
* @param total 金额,单位 元
* @param description 商品描述
* @param openid 微信用户的openid
* @return
*/
public JSONObject pay(String orderNum, BigDecimal total, String description, String openid) throws Exception {
//统一下单,生成预支付交易单
String bodyAsString = jsapi(orderNum, total, description, openid);
//解析返回结果
JSONObject jsonObject = JSON.parseObject(bodyAsString);
System.out.println(jsonObject);

String prepayId = jsonObject.getString("prepay_id");
if (prepayId != null) {
String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonceStr = RandomStringUtils.randomNumeric(32);
ArrayList<Object> list = new ArrayList<>();
list.add(weChatProperties.getAppid());
list.add(timeStamp);
list.add(nonceStr);
list.add("prepay_id=" + prepayId);
//二次签名,调起支付需要重新签名
StringBuilder stringBuilder = new StringBuilder();
for (Object o : list) {
stringBuilder.append(o).append("\n");
}
String signMessage = stringBuilder.toString();
byte[] message = signMessage.getBytes();

Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(PemUtil.loadPrivateKey(new FileInputStream(new File(weChatProperties.getPrivateKeyFilePath()))));
signature.update(message);
String packageSign = Base64.getEncoder().encodeToString(signature.sign());

//构造数据给微信小程序,用于调起微信支付
JSONObject jo = new JSONObject();
jo.put("timeStamp", timeStamp);
jo.put("nonceStr", nonceStr);
jo.put("package", "prepay_id=" + prepayId);
jo.put("signType", "RSA");
jo.put("paySign", packageSign);

return jo;
}
return jsonObject;
}

/**
* 申请退款
*
* @param outTradeNo 商户订单号
* @param outRefundNo 商户退款单号
* @param refund 退款金额
* @param total 原订单金额
* @return
*/
public String refund(String outTradeNo, String outRefundNo, BigDecimal refund, BigDecimal total) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no", outTradeNo);
jsonObject.put("out_refund_no", outRefundNo);

JSONObject amount = new JSONObject();
amount.put("refund", refund.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
amount.put("total", total.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
amount.put("currency", "CNY");

jsonObject.put("amount", amount);
jsonObject.put("notify_url", weChatProperties.getRefundNotifyUrl());

String body = jsonObject.toJSONString();

//调用申请退款接口
return post(REFUNDS, body);
}
}

BeanUtil

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
import cn.hutool.core.bean.BeanUtil;
import java.util.List;
import java.util.stream.Collectors;

/**
* 继承自 hutool 的BeanUtil,增加了bean转换时自定义转换器的功能
*/
public class BeanUtils extends BeanUtil {

/**
* 将原对象转换成目标对象,对于字段不匹配的字段可以使用转换器处理
*
* @param source 原对象
* @param clazz 目标对象的class
* @param convert 转换器
* @param <R> 原对象类型
* @param <T> 目标对象类型
* @return 目标对象
*/
public static <R, T> T copyBean(R source, Class<T> clazz, Convert<R, T> convert) {
T target = copyBean(source, clazz);
if (convert != null) {
convert.convert(source, target);
}
return target;
}
/**
* 将原对象转换成目标对象,对于字段不匹配的字段可以使用转换器处理
*
* @param source 原对象
* @param clazz 目标对象的class
* @param <R> 原对象类型
* @param <T> 目标对象类型
* @return 目标对象
*/
public static <R, T> T copyBean(R source, Class<T> clazz){
if (source == null) {
return null;
}
return toBean(source, clazz);
}

public static <R, T> List<T> copyList(List<R> list, Class<T> clazz) {
if (list == null || list.size() == 0) {
return CollUtils.emptyList();
}
return copyToList(list, clazz);
}

public static <R, T> List<T> copyList(List<R> list, Class<T> clazz, Convert<R, T> convert) {
if (list == null || list.size() == 0) {
return CollUtils.emptyList();
}
return list.stream().map(r -> copyBean(r, clazz, convert)).collect(Collectors.toList());
}
}

UserContext

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
import cn.hutool.core.bean.BeanUtil;
import java.util.List;
import java.util.stream.Collectors;

/**
* 继承自 hutool 的BeanUtil,增加了bean转换时自定义转换器的功能
*/
public class BeanUtils extends BeanUtil {

/**
* 将原对象转换成目标对象,对于字段不匹配的字段可以使用转换器处理
*
* @param source 原对象
* @param clazz 目标对象的class
* @param convert 转换器
* @param <R> 原对象类型
* @param <T> 目标对象类型
* @return 目标对象
*/
public static <R, T> T copyBean(R source, Class<T> clazz, Convert<R, T> convert) {
T target = copyBean(source, clazz);
if (convert != null) {
convert.convert(source, target);
}
return target;
}
/**
* 将原对象转换成目标对象,对于字段不匹配的字段可以使用转换器处理
*
* @param source 原对象
* @param clazz 目标对象的class
* @param <R> 原对象类型
* @param <T> 目标对象类型
* @return 目标对象
*/
public static <R, T> T copyBean(R source, Class<T> clazz){
if (source == null) {
return null;
}
return toBean(source, clazz);
}

public static <R, T> List<T> copyList(List<R> list, Class<T> clazz) {
if (list == null || list.size() == 0) {
return CollUtils.emptyList();
}
return copyToList(list, clazz);
}

public static <R, T> List<T> copyList(List<R> list, Class<T> clazz, Convert<R, T> convert) {
if (list == null || list.size() == 0) {
return CollUtils.emptyList();
}
return list.stream().map(r -> copyBean(r, clazz, convert)).collect(Collectors.toList());
}
}

WebUtil

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
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;

@Slf4j
public class WebUtils {

/**
* 获取ServletRequestAttributes
*
* @return ServletRequestAttributes
*/
public static ServletRequestAttributes getServletRequestAttributes() {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
if (ra == null) {
return null;
}
return (ServletRequestAttributes) ra;
}

/**
* 获取request
*
* @return HttpServletRequest
*/
public static HttpServletRequest getRequest() {
ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
return servletRequestAttributes == null ? null : servletRequestAttributes.getRequest();
}

/**
* 获取response
*
* @return HttpServletResponse
*/
public static HttpServletResponse getResponse() {
ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
return servletRequestAttributes == null ? null : servletRequestAttributes.getResponse();
}

/**
* 获取request header中的内容
*
* @param headerName 请求头名称
* @return 请求头的值
*/
public static String getHeader(String headerName) {
HttpServletRequest request = getRequest();
if (request == null) {
return null;
}
return getRequest().getHeader(headerName);
}

public static void setResponseHeader(String key, String value){
HttpServletResponse response = getResponse();
if (response == null) {
return;
}
response.setHeader(key, value);
}

public static boolean isSuccess() {
HttpServletResponse response = getResponse();
return response != null && response.getStatus() < 300;
}

/**
* 获取请求地址中的请求参数组装成 key1=value1&key2=value2
* 如果key对应多个值,中间使用逗号隔开例如 key1对应value1,key2对应value2,value3, key1=value1&key2=value2,value3
*
* @param request
* @return 返回拼接字符串
*/
public static String getParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
return getParameters(parameterMap);
}

/**
* 获取请求地址中的请求参数组装成 key1=value1&key2=value2
* 如果key对应多个值,中间使用逗号隔开例如 key1对应value1,key2对应value2,value3, key1=value1&key2=value2,value3
*
* @param queries
* @return
*/
public static <T> String getParameters(final Map<String, T> queries) {
StringBuilder buffer = new StringBuilder();
for (Map.Entry<String, T> entry : queries.entrySet()) {
if(entry.getValue() instanceof String[]){
buffer.append(entry.getKey()).append(String.join(",", ((String[])entry.getValue())))
.append("&");
}else if(entry.getValue() instanceof Collection){
buffer.append(entry.getKey()).append(
CollUtil.join(((Collection<String>)entry.getValue()),",")
).append("&");
}
}
return buffer.length() > 0 ? buffer.substring(0, buffer.length() - 1) : StrUtil.EMPTY;
}

/**
* 获取请求url中的uri
*
* @param url
* @return
*/
public static String getUri(String url){
if(StringUtils.isEmpty(url)) {
return null;
}

String uri = url;
//uri中去掉 http:// 或者https
if(uri.contains("http://") ){
uri = uri.replace("http://", StrUtil.EMPTY);
}else if(uri.contains("https://")){
uri = uri.replace("https://", StrUtil.EMPTY);
}

int endIndex = uri.length(); //uri 在url中的最后一个字符的序号+1
if(uri.contains("?")){
endIndex = uri.indexOf("?");
}
return uri.substring(uri.indexOf("/"), endIndex);
}

public static String getRemoteAddr() {
HttpServletRequest request = getRequest();
if (request == null) {
return "";
}
return request.getRemoteAddr();
}

public static CookieBuilder cookieBuilder(){
return new CookieBuilder(getRequest(), getResponse());
}
}

未完待续......