zoukankan      html  css  js  c++  java
  • Java工具类

    目录:

    1.HttpClientUtils 工具类

    2.阿里云视频点播工具类

    3.日期操作工具类

    4.MD5加密工具类

    5.Redis公共配置类

    6.响应工具类

    7.随机值工具类

    8.统一返回数据格式

    9.mybatis的时间自动注入

    10.JSON工具类

    11.jwt(token)工具类

    1.HttpClientUtils 工具类

      1 package com.atguigu.ucenterservice.utils;
      2 
      3 import org.apache.commons.io.IOUtils;
      4 import org.apache.commons.lang.StringUtils;
      5 import org.apache.http.Consts;
      6 import org.apache.http.HttpEntity;
      7 import org.apache.http.HttpResponse;
      8 import org.apache.http.NameValuePair;
      9 import org.apache.http.client.HttpClient;
     10 import org.apache.http.client.config.RequestConfig;
     11 import org.apache.http.client.config.RequestConfig.Builder;
     12 import org.apache.http.client.entity.UrlEncodedFormEntity;
     13 import org.apache.http.client.methods.HttpGet;
     14 import org.apache.http.client.methods.HttpPost;
     15 import org.apache.http.conn.ConnectTimeoutException;
     16 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
     17 import org.apache.http.conn.ssl.SSLContextBuilder;
     18 import org.apache.http.conn.ssl.TrustStrategy;
     19 import org.apache.http.conn.ssl.X509HostnameVerifier;
     20 import org.apache.http.entity.ContentType;
     21 import org.apache.http.entity.StringEntity;
     22 import org.apache.http.impl.client.CloseableHttpClient;
     23 import org.apache.http.impl.client.HttpClients;
     24 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
     25 import org.apache.http.message.BasicNameValuePair;
     26 
     27 import javax.net.ssl.SSLContext;
     28 import javax.net.ssl.SSLException;
     29 import javax.net.ssl.SSLSession;
     30 import javax.net.ssl.SSLSocket;
     31 import java.io.IOException;
     32 import java.net.SocketTimeoutException;
     33 import java.security.GeneralSecurityException;
     34 import java.security.cert.CertificateException;
     35 import java.security.cert.X509Certificate;
     36 import java.util.ArrayList;
     37 import java.util.List;
     38 import java.util.Map;
     39 import java.util.Map.Entry;
     40 import java.util.Set;
     41 
     42 /**
     43  *  依赖的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar
     44 
     45  *
     46  */
     47 public class HttpClientUtils {
     48 
     49     public static final int connTimeout=10000;
     50     public static final int readTimeout=10000;
     51     public static final String charset="UTF-8";
     52     private static HttpClient client = null;
     53 
     54     static {
     55         PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
     56         cm.setMaxTotal(128);
     57         cm.setDefaultMaxPerRoute(128);
     58         client = HttpClients.custom().setConnectionManager(cm).build();
     59     }
     60 
     61     public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
     62         return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
     63     }
     64 
     65     public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
     66         return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
     67     }
     68 
     69     public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
     70             SocketTimeoutException, Exception {
     71         return postForm(url, params, null, connTimeout, readTimeout);
     72     }
     73 
     74     public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
     75             SocketTimeoutException, Exception {
     76         return postForm(url, params, null, connTimeout, readTimeout);
     77     }
     78 
     79     public static String get(String url) throws Exception {
     80         return get(url, charset, null, null);
     81     }
     82 
     83     public static String get(String url, String charset) throws Exception {
     84         return get(url, charset, connTimeout, readTimeout);
     85     }
     86 
     87     /**
     88      * 发送一个 Post 请求, 使用指定的字符集编码.
     89      *
     90      * @param url
     91      * @param body RequestBody
     92      * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
     93      * @param charset 编码
     94      * @param connTimeout 建立链接超时时间,毫秒.
     95      * @param readTimeout 响应超时时间,毫秒.
     96      * @return ResponseBody, 使用指定的字符集编码.
     97      * @throws ConnectTimeoutException 建立链接超时异常
     98      * @throws SocketTimeoutException  响应超时
     99      * @throws Exception
    100      */
    101     public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
    102             throws ConnectTimeoutException, SocketTimeoutException, Exception {
    103         HttpClient client = null;
    104         HttpPost post = new HttpPost(url);
    105         String result = "";
    106         try {
    107             if (StringUtils.isNotBlank(body)) {
    108                 HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
    109                 post.setEntity(entity);
    110             }
    111             // 设置参数
    112             Builder customReqConf = RequestConfig.custom();
    113             if (connTimeout != null) {
    114                 customReqConf.setConnectTimeout(connTimeout);
    115             }
    116             if (readTimeout != null) {
    117                 customReqConf.setSocketTimeout(readTimeout);
    118             }
    119             post.setConfig(customReqConf.build());
    120 
    121             HttpResponse res;
    122             if (url.startsWith("https")) {
    123                 // 执行 Https 请求.
    124                 client = createSSLInsecureClient();
    125                 res = client.execute(post);
    126             } else {
    127                 // 执行 Http 请求.
    128                 client = HttpClientUtils.client;
    129                 res = client.execute(post);
    130             }
    131             result = IOUtils.toString(res.getEntity().getContent(), charset);
    132         } finally {
    133             post.releaseConnection();
    134             if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
    135                 ((CloseableHttpClient) client).close();
    136             }
    137         }
    138         return result;
    139     }
    140 
    141 
    142     /**
    143      * 提交form表单
    144      *
    145      * @param url
    146      * @param params
    147      * @param connTimeout
    148      * @param readTimeout
    149      * @return
    150      * @throws ConnectTimeoutException
    151      * @throws SocketTimeoutException
    152      * @throws Exception
    153      */
    154     public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
    155             SocketTimeoutException, Exception {
    156 
    157         HttpClient client = null;
    158         HttpPost post = new HttpPost(url);
    159         try {
    160             if (params != null && !params.isEmpty()) {
    161                 List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    162                 Set<Entry<String, String>> entrySet = params.entrySet();
    163                 for (Entry<String, String> entry : entrySet) {
    164                     formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    165                 }
    166                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
    167                 post.setEntity(entity);
    168             }
    169 
    170             if (headers != null && !headers.isEmpty()) {
    171                 for (Entry<String, String> entry : headers.entrySet()) {
    172                     post.addHeader(entry.getKey(), entry.getValue());
    173                 }
    174             }
    175             // 设置参数
    176             Builder customReqConf = RequestConfig.custom();
    177             if (connTimeout != null) {
    178                 customReqConf.setConnectTimeout(connTimeout);
    179             }
    180             if (readTimeout != null) {
    181                 customReqConf.setSocketTimeout(readTimeout);
    182             }
    183             post.setConfig(customReqConf.build());
    184             HttpResponse res = null;
    185             if (url.startsWith("https")) {
    186                 // 执行 Https 请求.
    187                 client = createSSLInsecureClient();
    188                 res = client.execute(post);
    189             } else {
    190                 // 执行 Http 请求.
    191                 client = HttpClientUtils.client;
    192                 res = client.execute(post);
    193             }
    194             return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
    195         } finally {
    196             post.releaseConnection();
    197             if (url.startsWith("https") && client != null
    198                     && client instanceof CloseableHttpClient) {
    199                 ((CloseableHttpClient) client).close();
    200             }
    201         }
    202     }
    203 
    204 
    205 
    206 
    207     /**
    208      * 发送一个 GET 请求
    209      *
    210      * @param url
    211      * @param charset
    212      * @param connTimeout  建立链接超时时间,毫秒.
    213      * @param readTimeout  响应超时时间,毫秒.
    214      * @return
    215      * @throws ConnectTimeoutException   建立链接超时
    216      * @throws SocketTimeoutException   响应超时
    217      * @throws Exception
    218      */
    219     public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
    220             throws ConnectTimeoutException,SocketTimeoutException, Exception {
    221 
    222         HttpClient client = null;
    223         HttpGet get = new HttpGet(url);
    224         String result = "";
    225         try {
    226             // 设置参数
    227             Builder customReqConf = RequestConfig.custom();
    228             if (connTimeout != null) {
    229                 customReqConf.setConnectTimeout(connTimeout);
    230             }
    231             if (readTimeout != null) {
    232                 customReqConf.setSocketTimeout(readTimeout);
    233             }
    234             get.setConfig(customReqConf.build());
    235 
    236             HttpResponse res = null;
    237 
    238             if (url.startsWith("https")) {
    239                 // 执行 Https 请求.
    240                 client = createSSLInsecureClient();
    241                 res = client.execute(get);
    242             } else {
    243                 // 执行 Http 请求.
    244                 client = HttpClientUtils.client;
    245                 res = client.execute(get);
    246             }
    247 
    248             result = IOUtils.toString(res.getEntity().getContent(), charset);
    249         } finally {
    250             get.releaseConnection();
    251             if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
    252                 ((CloseableHttpClient) client).close();
    253             }
    254         }
    255         return result;
    256     }
    257 
    258 
    259     /**
    260      * 从 response 里获取 charset
    261      *
    262      * @param ressponse
    263      * @return
    264      */
    265     @SuppressWarnings("unused")
    266     private static String getCharsetFromResponse(HttpResponse ressponse) {
    267         // Content-Type:text/html; charset=GBK
    268         if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
    269             String contentType = ressponse.getEntity().getContentType().getValue();
    270             if (contentType.contains("charset=")) {
    271                 return contentType.substring(contentType.indexOf("charset=") + 8);
    272             }
    273         }
    274         return null;
    275     }
    276 
    277 
    278 
    279     /**
    280      * 创建 SSL连接
    281      * @return
    282      * @throws GeneralSecurityException
    283      */
    284     private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
    285         try {
    286             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    287                 public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
    288                     return true;
    289                 }
    290             }).build();
    291 
    292             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
    293 
    294                 @Override
    295                 public boolean verify(String arg0, SSLSession arg1) {
    296                     return true;
    297                 }
    298 
    299                 @Override
    300                 public void verify(String host, SSLSocket ssl)
    301                         throws IOException {
    302                 }
    303 
    304                 @Override
    305                 public void verify(String host, X509Certificate cert)
    306                         throws SSLException {
    307                 }
    308 
    309                 @Override
    310                 public void verify(String host, String[] cns,
    311                                    String[] subjectAlts) throws SSLException {
    312                 }
    313 
    314             });
    315 
    316             return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    317 
    318         } catch (GeneralSecurityException e) {
    319             throw e;
    320         }
    321     }
    322 
    323     public static void main(String[] args) {
    324         try {
    325             String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);
    326             //String str= get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");
    327             /*Map<String,String> map = new HashMap<String,String>();
    328             map.put("name", "111");
    329             map.put("page", "222");
    330             String str= postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/
    331             System.out.println(str);
    332         } catch (ConnectTimeoutException e) {
    333             // TODO Auto-generated catch block
    334             e.printStackTrace();
    335         } catch (SocketTimeoutException e) {
    336             // TODO Auto-generated catch block
    337             e.printStackTrace();
    338         } catch (Exception e) {
    339             // TODO Auto-generated catch block
    340             e.printStackTrace();
    341         }
    342     }
    343 
    344 }
    HttpClientUtils

    2. 阿里云视频点播工具类

     1 import com.aliyuncs.DefaultAcsClient;
     2 import com.aliyuncs.exceptions.ClientException;
     3 import com.aliyuncs.profile.DefaultProfile;
     4 import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
     5 import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
     6 import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
     7 import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
     8 import com.atguigu.commonutils.ConstantUtil;
     9 import com.atguigu.servicebase.exception.GuliException;
    10 
    11 
    12 
    13 public class AliyunVodSDKUtils {
    14     public static DefaultAcsClient initVodClient(String accessKeyId, String accessKey){
    15         String regionId = "cn-shanghai"; // 点播服务接入区域
    16         DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKey);
    17         DefaultAcsClient client = new DefaultAcsClient(profile);
    18         return client;
    19     }
    20 
    21     public static String getVideoPlayAuth(String videoId){
    22         //初始化客户端、请求对象和相应对象
    23         DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(ConstantUtil.ACCESS_KEY_ID, ConstantUtil.ACCESS_KEY_SECRET);
    24         GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
    25         GetVideoPlayAuthResponse response ;
    26         String playAuth = "";
    27         try {
    28             //设置请求参数
    29             request.setVideoId(videoId);
    30             //获取请求响应
    31             response = client.getAcsResponse(request);
    32             //输出请求结果
    33             //播放凭证
    34             playAuth = response.getPlayAuth();
    35 
    36         } catch (Exception e) {
    37             System.out.print("ErrorMessage : " + e.getLocalizedMessage());
    38         }
    39 
    40         return playAuth;
    41     }
    42 
    43     public static void deleteVideo(String videoId){
    44         try{
    45             DefaultAcsClient client = initVodClient(ConstantUtil.ACCESS_KEY_ID, ConstantUtil.ACCESS_KEY_SECRET);
    46             DeleteVideoRequest request = new DeleteVideoRequest();
    47             request.setVideoIds(videoId);
    48             DeleteVideoResponse response = client.getAcsResponse(request);
    49             System.out.print("RequestId = " + response.getRequestId() + "
    ");
    50         }catch (ClientException e){
    51             throw new GuliException(20001, "视频删除失败");
    52         }
    53     }
    54 
    55 }
    AliyunVodSDKUtils

    3.日期操作工具类

     1 import java.text.SimpleDateFormat;
     2 import java.util.ArrayList;
     3 import java.util.Calendar;
     4 import java.util.Date;
     5 
     6 public class DateUtil {
     7 
     8     private static final String dateFormat = "yyyy-MM-dd";
     9 
    10     /**
    11      * 格式化日期
    12      *
    13      * @param date
    14      * @return
    15      */
    16     public static String formatDate(Date date) {
    17         SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    18         return sdf.format(date);
    19 
    20     }
    21 
    22     /**
    23      * 在日期date上增加amount天 。
    24      *
    25      * @param date   处理的日期,非null
    26      * @param amount 要加的天数,可能为负数
    27      */
    28     public static Date addDays(Date date, int amount) {
    29         Calendar now =Calendar.getInstance();
    30         now.setTime(date);
    31         now.set(Calendar.DATE,now.get(Calendar.DATE)+amount);
    32         return now.getTime();
    33     }
    34 
    35 
    36 }
    DateUtil

    4.MD5加密工具类

     1 import java.security.MessageDigest;
     2 import java.security.NoSuchAlgorithmException;
     3 
     4 
     5 public final class MD5 {
     6 
     7     public static String encrypt(String strSrc) {
     8         try {
     9             char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
    10                     '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    11             byte[] bytes = strSrc.getBytes();
    12             MessageDigest md = MessageDigest.getInstance("MD5");
    13             md.update(bytes);
    14             bytes = md.digest();
    15             int j = bytes.length;
    16             char[] chars = new char[j * 2];
    17             int k = 0;
    18             for (int i = 0; i < bytes.length; i++) {
    19                 byte b = bytes[i];
    20                 chars[k++] = hexChars[b >>> 4 & 0xf];
    21                 chars[k++] = hexChars[b & 0xf];
    22             }
    23             return new String(chars);
    24         } catch (NoSuchAlgorithmException e) {
    25             e.printStackTrace();
    26             throw new RuntimeException("MD5加密出错!!+" + e);
    27         }
    28     }
    29 
    30 
    31 }
    MD5

    5. Redis公共配置类

     1 import com.fasterxml.jackson.annotation.JsonAutoDetect;
     2 import com.fasterxml.jackson.annotation.PropertyAccessor;
     3 import com.fasterxml.jackson.databind.ObjectMapper;
     4 import org.springframework.cache.CacheManager;
     5 import org.springframework.cache.annotation.CachingConfigurerSupport;
     6 import org.springframework.cache.annotation.EnableCaching;
     7 import org.springframework.context.annotation.Bean;
     8 import org.springframework.context.annotation.Configuration;
     9 import org.springframework.data.redis.cache.RedisCacheConfiguration;
    10 import org.springframework.data.redis.cache.RedisCacheManager;
    11 import org.springframework.data.redis.connection.RedisConnectionFactory;
    12 import org.springframework.data.redis.core.RedisTemplate;
    13 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    14 import org.springframework.data.redis.serializer.RedisSerializationContext;
    15 import org.springframework.data.redis.serializer.RedisSerializer;
    16 import org.springframework.data.redis.serializer.StringRedisSerializer;
    17 
    18 import java.time.Duration;
    19 
    20 
    21 @EnableCaching
    22 @Configuration
    23 public class RedisConfig extends CachingConfigurerSupport {
    24     @Bean
    25     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
    26         RedisTemplate<String, Object> template = new RedisTemplate<>();
    27         RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    28         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    29         ObjectMapper om = new ObjectMapper();
    30         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    31         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    32         jackson2JsonRedisSerializer.setObjectMapper(om);
    33 
    34         template.setConnectionFactory(factory);
    35         //key序列化方式
    36         template.setKeySerializer(redisSerializer);
    37         //value序列化
    38         template.setValueSerializer(jackson2JsonRedisSerializer);
    39         //value hashmap序列化
    40         template.setHashValueSerializer(jackson2JsonRedisSerializer);
    41         return template;
    42     }
    43 
    44     @Bean
    45     public CacheManager cacheManager(RedisConnectionFactory factory) {
    46         RedisSerializer<String> redisSerializer = new StringRedisSerializer();
    47         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    48         //解决查询缓存转换异常的问题
    49         ObjectMapper om = new ObjectMapper();
    50         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    51         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    52         jackson2JsonRedisSerializer.setObjectMapper(om);
    53 
    54         // 配置序列化(解决乱码的问题),过期时间600秒
    55         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
    56                 .entryTtl(Duration.ofSeconds(600))
    57                 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
    58                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
    59                 .disableCachingNullValues();
    60         RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
    61                 .cacheDefaults(config)
    62                 .build();
    63         return cacheManager;
    64     }
    65 }
    RedisConfig
    1  @Autowired
    2  private RedisTemplate redisTemplate;

    6.响应工具类

     1 import com.atguigu.commonutils.R;
     2 import com.fasterxml.jackson.databind.ObjectMapper;
     3 import org.springframework.http.HttpStatus;
     4 import org.springframework.http.MediaType;
     5 
     6 import javax.servlet.http.HttpServletResponse;
     7 import java.io.IOException;
     8 
     9 public class ResponseUtil {
    10 
    11     public static void out(HttpServletResponse response, R r) {
    12         ObjectMapper mapper = new ObjectMapper();
    13         response.setStatus(HttpStatus.OK.value());
    14         response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    15         try {
    16             // mapper.writeValue(response.getWriter(), r);
    17             mapper.writeValue(response.getOutputStream(), r);
    18         } catch (IOException e) {
    19             e.printStackTrace();
    20         }
    21     }
    22 }
    ResponseUtil

    7. 随机值工具类

     1 import java.text.DecimalFormat;
     2 import java.util.ArrayList;
     3 import java.util.HashMap;
     4 import java.util.List;
     5 import java.util.Random;
     6 
     7 /**
     8  * 获取随机数*/
     9 public class RandomUtil {
    10 
    11     private static final Random random = new Random();
    12 
    13     private static final DecimalFormat fourdf = new DecimalFormat("0000");
    14 
    15     private static final DecimalFormat sixdf = new DecimalFormat("000000");
    16 
    17     public static String getFourBitRandom() {
    18         return fourdf.format(random.nextInt(10000));
    19     }
    20 
    21     public static String getSixBitRandom() {
    22         return sixdf.format(random.nextInt(1000000));
    23     }
    24 
    25     /**
    26      * 给定数组,抽取n个数据
    27      * @param list
    28      * @param n
    29      * @return
    30      */
    31     public static ArrayList getRandom(List list, int n) {
    32 
    33         Random random = new Random();
    34 
    35         HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
    36 
    37         // 生成随机数字并存入HashMap
    38         for (int i = 0; i < list.size(); i++) {
    39 
    40             int number = random.nextInt(100) + 1;
    41 
    42             hashMap.put(number, i);
    43         }
    44 
    45         // 从HashMap导入数组
    46         Object[] robjs = hashMap.values().toArray();
    47 
    48         ArrayList r = new ArrayList();
    49 
    50         // 遍历数组并打印数据
    51         for (int i = 0; i < n; i++) {
    52             r.add(list.get((int) robjs[i]));
    53             System.out.print(list.get((int) robjs[i]) + "	");
    54         }
    55         System.out.print("
    ");
    56         return r;
    57     }
    58 }
    RandomUtil

    8. 统一返回数据格式

     1 @Data
     2 public class R {
     3     @ApiModelProperty(value = "是否成功")
     4     private Boolean success;
     5     @ApiModelProperty(value = "返回码")
     6     private Integer code;
     7     @ApiModelProperty(value = "返回消息")
     8     private String message;
     9     @ApiModelProperty(value = "返回数据")
    10     private Map<String, Object> data = new HashMap<String, Object>();
    11 
    12     private R(){}
    13 
    14     public static R ok(){
    15         R r = new R();
    16         r.setSuccess(true);
    17         r.setCode(ResultCode.SUCCESS);
    18         r.setMessage("成功");
    19         return r;
    20     }
    21 
    22     public static R error(){
    23         R r = new R();
    24         r.setSuccess(false);
    25         r.setCode(ResultCode.ERROR);
    26         r.setMessage("失败");
    27         return r;
    28     }
    29 
    30     public R success(Boolean success){
    31         this.setSuccess(success);
    32         return this;
    33     }
    34 
    35     public R message(String message){
    36         this.setMessage(message);
    37         return this;
    38     }
    39 
    40     public R code(Integer code){
    41         this.setCode(code);
    42         return this;
    43     }
    44 
    45     public R data(String key, Object value){
    46         this.data.put(key, value);
    47         return this;
    48     }
    49 
    50     public R data(Map<String, Object> map){
    51         this.setData(map);
    52         return this;
    53     }
    54 
    55 }
    R
    1 public interface ResultCode {
    2      public static Integer SUCCESS = 20000;
    3      public static Integer ERROR = 20001;
    4  }
    ResultCode

     9. mybatis的时间自动注入

     1 import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
     2 import org.apache.ibatis.reflection.MetaObject;
     3 import org.springframework.stereotype.Component;
     4 
     5 import java.util.Date;
     6 
     7 /**
     8    * gmtCreate
     9    * gmtModified
    10    * 此处两个时间根据自己的设置
    11 **/
    12 @Component
    13 public class MyMetaObjectHandler implements MetaObjectHandler {
    14     @Override
    15     public void insertFill(MetaObject metaObject) {
    16         this.setFieldValByName("gmtCreate", new Date(), metaObject);
    17         this.setFieldValByName("gmtModified", new Date(), metaObject);
    18     }
    19     @Override
    20     public void updateFill(MetaObject metaObject) {
    21         this.setFieldValByName("gmtModified", new Date(), metaObject);
    22     }
    23 }    
    View Code
    1 // 在实体类的字段上加上该注解
    2 @TableField(fill = FieldFill.INSERT)    //创建时间
    3 @TableField(fill = FieldFill.INSERT_UPDATE)       // 更新时间

     10. JSON工具类

    import java.util.List;
    import java.util.Map;
     
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.serializer.PropertyFilter;
    import com.alibaba.fastjson.serializer.SerializerFeature;
     
    /**
     * 在系统中统一使用这个,以方便将来切换不同的JSON生成工具
     * 
     * @author KelvinZ
     * 
     */
    public class JsonUtils {
    public static final int TYPE_FASTJSON = 0;
    public static final int TYPE_GSON = 1;
     
    /**
     * <pre>
     * 对象转化为json字符串
     * 
     * @param obj 待转化对象
     * @return 代表该对象的Json字符串
     */
    public static final String toJson(final Object obj) {
    return JSON.toJSONString(obj);
    // return gson.toJson(obj);
    }
     
    /**
     * <pre>
     * 对象转化为json字符串
     * 
     * @param obj 待转化对象
     * @return 代表该对象的Json字符串
     */
    public static final String toJson(final Object obj, SerializerFeature... features) {
    return JSON.toJSONString(obj, features);
    // return gson.toJson(obj);
    }
     
    /**
     * 对象转化为json字符串并格式化
     * 
     * @param obj
     * @param format 是否要格式化
     * @return
     */
    public static final String toJson(final Object obj, final boolean format) {
    return JSON.toJSONString(obj, format);
    }
     
    /**
     * 对象对指定字段进行过滤处理,生成json字符串
     * 
     * @param obj
     * @param fields 过滤处理字段
     * @param ignore true做忽略处理,false做包含处理
     * @param features json特征,为null忽略
     * @return
     */
    public static final String toJson(final Object obj, final String[] fields, final boolean ignore,
    SerializerFeature... features) {
    if (fields == null || fields.length < 1) {
    return toJson(obj);
    }
    if (features == null)
    features = new SerializerFeature[] { SerializerFeature.QuoteFieldNames };
    return JSON.toJSONString(obj, new PropertyFilter() {
    @Override
    public boolean apply(Object object, String name, Object value) {
    for (int i = 0; i < fields.length; i++) {
    if (name.equals(fields[i])) {
    return !ignore;
    }
    }
    return ignore;
    }
    }, features);
    }
     
    /**
     * <pre>
     * 解析json字符串中某路径的值
     * 
     * @param json
     * @param path
     * @return
     */
    @SuppressWarnings("unchecked")
    public static final <E> E parse(final String json, final String path) {
    String[] keys = path.split(",");
    JSONObject obj = JSON.parseObject(json);
    for (int i = 0; i < keys.length - 1; i++) {
    obj = obj.getJSONObject(keys[i]);
    }
    return (E) obj.get(keys[keys.length - 1]);
    }
     
    /**
     * <pre>
     * json字符串解析为对象
     * 
     * @param json 代表一个对象的Json字符串
     * @param clazz 指定目标对象的类型,即返回对象的类型
     * @return 从json字符串解析出来的对象
     */
    public static final <T> T parse(final String json, final Class<T> clazz) {
    return JSON.parseObject(json, clazz);
    }
     
    /**
     * <pre>
     * json字符串解析为对象
     * 
     * @param json json字符串
     * @param path 逗号分隔的json层次结构
     * @param clazz 目标类
     */
    public static final <T> T parse(final String json, final String path, final Class<T> clazz) {
    String[] keys = path.split(",");
    JSONObject obj = JSON.parseObject(json);
    for (int i = 0; i < keys.length - 1; i++) {
    obj = obj.getJSONObject(keys[i]);
    }
    String inner = obj.getString(keys[keys.length - 1]);
    return parse(inner, clazz);
    }
     
    /**
     * 将制定的对象经过字段过滤处理后,解析成为json集合
     * 
     * @param obj
     * @param fields
     * @param ignore
     * @param clazz
     * @param features
     * @return
     */
    public static final <T> List<T> parseArray(final Object obj, final String[] fields, boolean ignore,
    final Class<T> clazz, final SerializerFeature... features) {
    String json = toJson(obj, fields, ignore, features);
    return parseArray(json, clazz);
    }
     
    /**
     * <pre>
     * 从json字符串中解析出一个对象的集合,被解析字符串要求是合法的集合类型
     * (形如:["k1":"v1","k2":"v2",..."kn":"vn"])
     * 
     * @param json - [key-value-pair...]
     * @param clazz
     * @return
     */
    public static final <T> List<T> parseArray(final String json, final Class<T> clazz) {
    return JSON.parseArray(json, clazz);
    }
     
    /**
     * <pre>
     * 从json字符串中按照路径寻找,并解析出一个对象的集合,例如:
     * 类Person有一个属性name,要从以下json中解析出其集合:
     * {
     * "page_info":{
     * "items":{
     * "item":[{"name":"KelvinZ"},{"name":"Jobs"},...{"name":"Gates"}]
     * }
     * }
     * 使用方法:parseArray(json, "page_info,items,item", Person.class),
     * 将根据指定路径,正确的解析出所需集合,排除外层干扰
     * 
     * @param json json字符串
     * @param path 逗号分隔的json层次结构
     * @param clazz 目标类
     * @return
     */
    public static final <T> List<T> parseArray(final String json, final String path, final Class<T> clazz) {
    String[] keys = path.split(",");
    JSONObject obj = JSON.parseObject(json);
    for (int i = 0; i < keys.length - 1; i++) {
    obj = obj.getJSONObject(keys[i]);
    }
    String inner = obj.getString(keys[keys.length - 1]);
    List<T> ret = parseArray(inner, clazz);
    return ret;
    }
     
    /**
     * <pre>
     * 有些json的常见格式错误这里可以处理,以便给后续的方法处理
     * 常见错误:使用了" 或者 "{ 或者 }",腾讯的页面中常见这种格式
     * 
     * @param invalidJson 包含非法格式的json字符串
     * @return
     */
    public static final String correctJson(final String invalidJson) {
    String content = invalidJson.replace("\"", """).replace(""{", "{").replace("}"", "}");
    return content;
    }
     
    /**
     * 格式化Json
     * 
     * @param json
     * @return
     */
    public static final String formatJson(String json) {
    Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
    return JSON.toJSONString(map, true);
    }
     
    /**
     * 获取json串中的子json
     * 
     * @param json
     * @param path
     * @return
     */
    public static final String getSubJson(String json, String path) {
    String[] keys = path.split(",");
    JSONObject obj = JSON.parseObject(json);
    for (int i = 0; i < keys.length - 1; i++) {
    obj = obj.getJSONObject(keys[i]);
    System.out.println(obj.toJSONString());
    }
    return obj != null ? obj.getString(keys[keys.length - 1]) : null;
    }
     
    }
    View Code

    11.jwt(token)工具类

    import io.jsonwebtoken.CompressionCodecs;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    /**
     * <p>
     * token管理
     * </p>
     *
     * @author qy
     * @since 2019-11-08
     */
    @Component
    public class TokenManager {
    
        private long tokenExpiration = 24*60*60*1000;
        private String tokenSignKey = "123456";
    
        public String createToken(String username) {
            String token = Jwts.builder().setSubject(username)
                    .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                    .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                    .compressWith(CompressionCodecs.GZIP)
                    .compact();
            return token;
        }
    
        public String getUserFromToken(String token) {
            String user = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
            return user;
        }
    
        public void removeToken(String token) {
            //jwttoken无需删除,客户端扔掉即可。
        }
    
    }
    View Code
    作者:zhangshuai
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Regex一些基本的方法
    正则表达式中特殊字符的含义
    demo_36 收藏与点赞功能实现_02
    demo_36 收藏与点赞功能实现_01
    demo_35 关注作者_02 关注作者功能实现
    demo_35 关注作者_01 云函数实现
    demo_34 评论内容实现_6 实现对子回复的回复
    demo_34 评论内容实现_5 对回复的回复的逻辑实现并渲染到页面
    demo_34 评论内容实现_4 实现对评论的评论
    demo_34 评论内容实现_3 从数据库加载评论
  • 原文地址:https://www.cnblogs.com/zhangshaui/p/15062341.html
Copyright © 2011-2022 走看看