• 根据token和url、参数判断时间内是否重复提交


    RepeatSubmit 根据token和url、参数判断时间内是否重复提交

    如果请求头中有token(可指定其他变量作为唯一标识)则以该变量作为key存储map(url,参数含时间)

    如果请求头中没有token(可指定其他变量作为唯一标识),可以用url作为key判断url和参数在指定时间内是否请求过。

    结构

    在这里插入图片描述

    使用

        @PostMapping("/test")
        @RepeatSubmit
        public R add(@RequestBody String name) {
        return R.ok();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    RepeatSubmitInterceptor

    package com.yymt.common.config;
    
    import com.alibaba.fastjson.JSONObject;
    
    import com.yymt.common.annotation.RepeatSubmit;
    import com.yymt.common.utils.R;
    import com.yymt.common.utils.ServletUtils;
    import org.springframework.stereotype.Component;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.lang.reflect.Method;
    
    /**
     * 防止重复提交拦截器
     *
     * @author ruoyi
     */
    @Component
    public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
                RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
                if (annotation != null) {
                    if (this.isRepeatSubmit(request, annotation)) {
                        // AjaxResult ajaxResult = AjaxResult.error(annotation.message());
                        R error = R.error(annotation.message());
                        ServletUtils.renderString(response, JSONObject.toJSONString(error));
                        return false;
                    }
                }
                return true;
            } else {
                return true;
            }
        }
    
        /**
         * 验证是否重复提交由子类实现具体的防重复提交的规则
         *
         * @param request
         * @return
         * @throws Exception
         */
        public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
    }
    
    
    • 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

    SameUrlDataInterceptor

    package com.yymt.common.config;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.yymt.common.annotation.RepeatSubmit;
    import com.yymt.common.constants.Constant;
    import com.yymt.common.utils.RedisUtils;
    import com.yymt.common.utils.StringUtils;
    import com.yymt.common.utils.http.HttpHelper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 判断请求url和数据是否和上一次相同,
     * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。
     *
     * @author ruoyi
     */
    @Component
    public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {
        public final String REPEAT_PARAMS = "repeatParams";
    
        public final String REPEAT_TIME = "repeatTime";
    
        // private String header = "Authorization";
        private String header = "x-user-id";
    
        @Autowired
        private RedisUtils redisUtils;
    
        @SuppressWarnings("unchecked")
        @Override
        public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) {
            String nowParams = "";
            if (request instanceof RepeatedlyRequestWrapper) {
                RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
                nowParams = HttpHelper.getBodyString(repeatedlyRequest);
            }
    
            // body参数为空,获取Parameter的数据
            if (StringUtils.isEmpty(nowParams)) {
                nowParams = JSONObject.toJSONString(request.getParameterMap());
            }
            Map<String, Object> nowDataMap = new HashMap<String, Object>();
            nowDataMap.put(REPEAT_PARAMS, nowParams);
            nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
    
            // 请求地址(作为存放cache的key值)
            String url = request.getRequestURI();
    
            // 唯一值(没有消息头则使用请求地址)
            String submitKey = request.getHeader(header);
            if (StringUtils.isEmpty(submitKey)) {
                submitKey = url;
            }
    
            // 唯一标识(指定key + 消息头)
            String cacheRepeatKey = Constant.REPEAT_SUBMIT_KEY + submitKey;
    
            // Object sessionObj = redisUtils.get(cacheRepeatKey);
            Map<String, Object> sessionObj =  JSON.parseObject(redisUtils.get(cacheRepeatKey), Map.class);
            // .getCacheObject(cacheRepeatKey);
            if (sessionObj != null) {
                Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
                if (sessionMap.containsKey(url)) {
                    Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
                    if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) {
                        return true;
                    }
                }
            }
            Map<String, Object> cacheMap = new HashMap<String, Object>();
            cacheMap.put(url, nowDataMap);
            redisUtils.set(cacheRepeatKey, cacheMap, annotation.interval());
            // redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS);
            return false;
        }
    
        /**
         * 判断参数是否相同
         */
        private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) {
            String nowParams = (String) nowMap.get(REPEAT_PARAMS);
            String preParams = (String) preMap.get(REPEAT_PARAMS);
            return nowParams.equals(preParams);
        }
    
        /**
         * 判断两次间隔时间
         */
        private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval) {
            long time1 = (Long) nowMap.get(REPEAT_TIME);
            long time2 = (Long) preMap.get(REPEAT_TIME);
            if ((time1 - time2) < interval) {
                return true;
            }
            return false;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        }
    
    }
    
    
    • 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

    RepeatSubmit

    package com.yymt.common.annotation;
    
    import java.lang.annotation.*;
    
    /**
     * 自定义注解防止表单重复提交
     *
     * @author ruoyi
     *
     */
    @Inherited
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface RepeatSubmit
    {
        /**
         * 间隔时间(ms),小于此时间视为重复提交
         */
        public int interval() default 3500;
    
        /**
         * 提示消息
         */
        public String message() default "不允许重复提交,请稍候再试";
    }
    
    
    • 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

    WebMvcConfig

    package com.yymt.config;
    
    import com.yymt.common.config.RepeatSubmitInterceptor;
    import com.yymt.interceptor.AuthInterceptor;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * MVC配置
     */
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        @Autowired
        private AuthInterceptor authInterceptor;
        @Autowired
        private RepeatSubmitInterceptor repeatSubmitInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(authInterceptor).addPathPatterns("/**");
    	    registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
        }
    
    	@Override
    	public void addResourceHandlers(ResourceHandlerRegistry registry) {
    		registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
    	}
    
        /**
         * 跨域支持
         */
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*").allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH").maxAge(3600 * 24);
        }
    }
    
    • 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

    RepeatedlyRequestWrapper

    package com.yymt.common.config;
    
    
    import com.yymt.common.utils.http.HttpHelper;
    
    import javax.servlet.ReadListener;
    import javax.servlet.ServletInputStream;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletRequestWrapper;
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    /**
     * 构建可重复读取inputStream的request
     * 
     * @author ruoyi
     */
    public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper
    {
        private final byte[] body;
    
        public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException
        {
            super(request);
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
    
            body = HttpHelper.getBodyString(request).getBytes("UTF-8");
        }
    
        @Override
        public BufferedReader getReader() throws IOException
        {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }
    
        @Override
        public ServletInputStream getInputStream() throws IOException
        {
            final ByteArrayInputStream bais = new ByteArrayInputStream(body);
            return new ServletInputStream()
            {
                @Override
                public int read() throws IOException
                {
                    return bais.read();
                }
    
                @Override
                public int available() throws IOException
                {
                    return body.length;
                }
    
                @Override
                public boolean isFinished()
                {
                    return false;
                }
    
                @Override
                public boolean isReady()
                {
                    return false;
                }
    
                @Override
                public void setReadListener(ReadListener readListener)
                {
    
                }
            };
        }
    }
    
    
    • 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

    其他:

    HttpUtils

    package com.yymt.common.utils.http;
    
    
    import com.yymt.common.constants.Constant;
    import com.yymt.common.utils.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.net.ssl.*;
    import java.io.*;
    import java.net.ConnectException;
    import java.net.SocketTimeoutException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.security.cert.X509Certificate;
    
    /**
     * 通用http发送方法
     * 
     * @author ruoyi
     */
    public class HttpUtils
    {
        private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    
        /**
         * 向指定 URL 发送GET方法的请求
         *
         * @param url 发送请求的 URL
         * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static String sendGet(String url, String param)
        {
            return sendGet(url, param, Constant.UTF8);
        }
    
        /**
         * 向指定 URL 发送GET方法的请求
         *
         * @param url 发送请求的 URL
         * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @param contentType 编码类型
         * @return 所代表远程资源的响应结果
         */
        public static String sendGet(String url, String param, String contentType)
        {
            StringBuilder result = new StringBuilder();
            BufferedReader in = null;
            try
            {
                String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
                log.info("sendGet - {}", urlNameString);
                URL realUrl = new URL(urlNameString);
                URLConnection connection = realUrl.openConnection();
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                connection.connect();
                in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
                String line;
                while ((line = in.readLine()) != null)
                {
                    result.append(line);
                }
                log.info("recv - {}", result);
            }
            catch (ConnectException e)
            {
                log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
            }
            catch (SocketTimeoutException e)
            {
                log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
            }
            catch (IOException e)
            {
                log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
            }
            catch (Exception e)
            {
                log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
            }
            finally
            {
                try
                {
                    if (in != null)
                    {
                        in.close();
                    }
                }
                catch (Exception ex)
                {
                    log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                }
            }
            return result.toString();
        }
    
        /**
         * 向指定 URL 发送POST方法的请求
         *
         * @param url 发送请求的 URL
         * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static String sendPost(String url, String param)
        {
            PrintWriter out = null;
            BufferedReader in = null;
            StringBuilder result = new StringBuilder();
            try
            {
                String urlNameString = url;
                log.info("sendPost - {}", urlNameString);
                URL realUrl = new URL(urlNameString);
                URLConnection conn = realUrl.openConnection();
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                conn.setRequestProperty("Accept-Charset", "utf-8");
                conn.setRequestProperty("contentType", "utf-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                out = new PrintWriter(conn.getOutputStream());
                out.print(param);
                out.flush();
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                String line;
                while ((line = in.readLine()) != null)
                {
                    result.append(line);
                }
                log.info("recv - {}", result);
            }
            catch (ConnectException e)
            {
                log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
            }
            catch (SocketTimeoutException e)
            {
                log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
            }
            catch (IOException e)
            {
                log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
            }
            catch (Exception e)
            {
                log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
            }
            finally
            {
                try
                {
                    if (out != null)
                    {
                        out.close();
                    }
                    if (in != null)
                    {
                        in.close();
                    }
                }
                catch (IOException ex)
                {
                    log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
                }
            }
            return result.toString();
        }
    
        public static String sendSSLPost(String url, String param)
        {
            StringBuilder result = new StringBuilder();
            String urlNameString = url + "?" + param;
            try
            {
                log.info("sendSSLPost - {}", urlNameString);
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
                URL console = new URL(urlNameString);
                HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                conn.setRequestProperty("Accept-Charset", "utf-8");
                conn.setRequestProperty("contentType", "utf-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
    
                conn.setSSLSocketFactory(sc.getSocketFactory());
                conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String ret = "";
                while ((ret = br.readLine()) != null)
                {
                    if (ret != null && !"".equals(ret.trim()))
                    {
                        result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                    }
                }
                log.info("recv - {}", result);
                conn.disconnect();
                br.close();
            }
            catch (ConnectException e)
            {
                log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
            }
            catch (SocketTimeoutException e)
            {
                log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
            }
            catch (IOException e)
            {
                log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
            }
            catch (Exception e)
            {
                log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
            }
            return result.toString();
        }
    
        private static class TrustAnyTrustManager implements X509TrustManager
        {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
            {
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
            {
            }
    
            @Override
            public X509Certificate[] getAcceptedIssuers()
            {
                return new X509Certificate[] {};
            }
        }
    
        private static class TrustAnyHostnameVerifier implements HostnameVerifier
        {
            @Override
            public boolean verify(String hostname, SSLSession session)
            {
                return true;
            }
        }
    }
    
    • 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
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256

    ServletUtils

    package com.yymt.common.utils;
    
    import cn.hutool.core.convert.Convert;
    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 javax.servlet.http.HttpSession;
    import java.io.IOException;
    
    /**
     * 客户端工具类
     * 
     * @author ruoyi
     */
    public class ServletUtils
    {
        /**
         * 获取String参数
         */
        public static String getParameter(String name)
        {
            return getRequest().getParameter(name);
        }
    
        /**
         * 获取String参数
         */
        public static String getParameter(String name, String defaultValue)
        {
            return Convert.toStr(getRequest().getParameter(name), defaultValue);
        }
    
        /**
         * 获取Integer参数
         */
        public static Integer getParameterToInt(String name)
        {
            return Convert.toInt(getRequest().getParameter(name));
        }
    
        /**
         * 获取Integer参数
         */
        public static Integer getParameterToInt(String name, Integer defaultValue)
        {
            return Convert.toInt(getRequest().getParameter(name), defaultValue);
        }
    
        /**
         * 获取Boolean参数
         */
        public static Boolean getParameterToBool(String name)
        {
            return Convert.toBool(getRequest().getParameter(name));
        }
    
        /**
         * 获取Boolean参数
         */
        public static Boolean getParameterToBool(String name, Boolean defaultValue)
        {
            return Convert.toBool(getRequest().getParameter(name), defaultValue);
        }
    
        /**
         * 获取request
         */
        public static HttpServletRequest getRequest()
        {
            return getRequestAttributes().getRequest();
        }
    
        /**
         * 获取response
         */
        public static HttpServletResponse getResponse()
        {
            return getRequestAttributes().getResponse();
        }
    
        /**
         * 获取session
         */
        public static HttpSession getSession()
        {
            return getRequest().getSession();
        }
    
        public static ServletRequestAttributes getRequestAttributes()
        {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes) attributes;
        }
    
        /**
         * 将字符串渲染到客户端
         * 
         * @param response 渲染对象
         * @param string 待渲染的字符串
         * @return null
         */
        public static String renderString(HttpServletResponse response, String string)
        {
            try
            {
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(string);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 是否是Ajax异步请求
         * 
         * @param request
         */
        public static boolean isAjaxRequest(HttpServletRequest request)
        {
            String accept = request.getHeader("accept");
            if (accept != null && accept.indexOf("application/json") != -1)
            {
                return true;
            }
    
            String xRequestedWith = request.getHeader("X-Requested-With");
            if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1)
            {
                return true;
            }
    
            String uri = request.getRequestURI();
            if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml"))
            {
                return true;
            }
    
            String ajax = request.getParameter("__ajax");
            if (StringUtils.inStringIgnoreCase(ajax, "json", "xml"))
            {
                return true;
            }
            return false;
        }
    }
    
    
    • 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

    HttpHelper

    package com.yymt.common.utils.http;
    
    import org.apache.commons.lang3.exception.ExceptionUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.servlet.ServletRequest;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.nio.charset.Charset;
    
    /**
     * 通用http工具封装
     * 
     * @author ruoyi
     */
    public class HttpHelper
    {
        private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class);
    
        public static String getBodyString(ServletRequest request)
        {
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = null;
            try (InputStream inputStream = request.getInputStream())
            {
                reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
                String line = "";
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line);
                }
            }
            catch (IOException e)
            {
                LOGGER.warn("getBodyString出现问题!");
            }
            finally
            {
                if (reader != null)
                {
                    try
                    {
                        reader.close();
                    }
                    catch (IOException e)
                    {
                        LOGGER.error(ExceptionUtils.getMessage(e));
                    }
                }
            }
            return sb.toString();
        }
    }
    
    
    • 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

    Convert

    package com.yymt.common.utils.text;
    
    import com.yymt.common.utils.StringUtils;
    import org.apache.commons.lang3.ArrayUtils;
    
    import java.math.BigDecimal;
    import java.math.BigInteger;
    import java.nio.ByteBuffer;
    import java.nio.charset.Charset;
    import java.text.NumberFormat;
    import java.util.Set;
    
    /**
     * 类型转换器
     *
     * @author ruoyi
     */
    public class Convert {
        /**
         * 转换为字符串<br>
         * 如果给定的值为null,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static String toStr(Object value, String defaultValue) {
            if (null == value) {
                return defaultValue;
            }
            if (value instanceof String) {
                return (String) value;
            }
            return value.toString();
        }
    
        /**
         * 转换为字符串<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static String toStr(Object value) {
            return toStr(value, null);
        }
    
        /**
         * 转换为字符<br>
         * 如果给定的值为null,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Character toChar(Object value, Character defaultValue) {
            if (null == value) {
                return defaultValue;
            }
            if (value instanceof Character) {
                return (Character) value;
            }
    
            final String valueStr = toStr(value, null);
            return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);
        }
    
        /**
         * 转换为字符<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Character toChar(Object value) {
            return toChar(value, null);
        }
    
        /**
         * 转换为byte<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Byte toByte(Object value, Byte defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Byte) {
                return (Byte) value;
            }
            if (value instanceof Number) {
                return ((Number) value).byteValue();
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return Byte.parseByte(valueStr);
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为byte<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Byte toByte(Object value) {
            return toByte(value, null);
        }
    
        /**
         * 转换为Short<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Short toShort(Object value, Short defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Short) {
                return (Short) value;
            }
            if (value instanceof Number) {
                return ((Number) value).shortValue();
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return Short.parseShort(valueStr.trim());
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为Short<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Short toShort(Object value) {
            return toShort(value, null);
        }
    
        /**
         * 转换为Number<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Number toNumber(Object value, Number defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Number) {
                return (Number) value;
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return NumberFormat.getInstance().parse(valueStr);
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为Number<br>
         * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Number toNumber(Object value) {
            return toNumber(value, null);
        }
    
        /**
         * 转换为int<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Integer toInt(Object value, Integer defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Integer) {
                return (Integer) value;
            }
            if (value instanceof Number) {
                return ((Number) value).intValue();
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return Integer.parseInt(valueStr.trim());
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为int<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Integer toInt(Object value) {
            return toInt(value, null);
        }
    
        /**
         * 转换为Integer数组<br>
         *
         * @param str 被转换的值
         * @return 结果
         */
        public static Integer[] toIntArray(String str) {
            return toIntArray(",", str);
        }
    
        /**
         * 转换为Long数组<br>
         *
         * @param str 被转换的值
         * @return 结果
         */
        public static Long[] toLongArray(String str) {
            return toLongArray(",", str);
        }
    
        /**
         * 转换为Integer数组<br>
         *
         * @param split 分隔符
         * @param split 被转换的值
         * @return 结果
         */
        public static Integer[] toIntArray(String split, String str) {
            if (StringUtils.isEmpty(str)) {
                return new Integer[]{};
            }
            String[] arr = str.split(split);
            final Integer[] ints = new Integer[arr.length];
            for (int i = 0; i < arr.length; i++) {
                final Integer v = toInt(arr[i], 0);
                ints[i] = v;
            }
            return ints;
        }
    
        /**
         * 转换为Long数组<br>
         *
         * @param split 分隔符
         * @param str   被转换的值
         * @return 结果
         */
        public static Long[] toLongArray(String split, String str) {
            if (StringUtils.isEmpty(str)) {
                return new Long[]{};
            }
            String[] arr = str.split(split);
            final Long[] longs = new Long[arr.length];
            for (int i = 0; i < arr.length; i++) {
                final Long v = toLong(arr[i], null);
                longs[i] = v;
            }
            return longs;
        }
    
        /**
         * 转换为String数组<br>
         *
         * @param str 被转换的值
         * @return 结果
         */
        public static String[] toStrArray(String str) {
            return toStrArray(",", str);
        }
    
        /**
         * 转换为String数组<br>
         *
         * @param split 分隔符
         * @param split 被转换的值
         * @return 结果
         */
        public static String[] toStrArray(String split, String str) {
            return str.split(split);
        }
    
        /**
         * 转换为long<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Long toLong(Object value, Long defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Long) {
                return (Long) value;
            }
            if (value instanceof Number) {
                return ((Number) value).longValue();
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                // 支持科学计数法
                return new BigDecimal(valueStr.trim()).longValue();
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为long<br>
         * 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Long toLong(Object value) {
            return toLong(value, null);
        }
    
        /**
         * 转换为double<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Double toDouble(Object value, Double defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Double) {
                return (Double) value;
            }
            if (value instanceof Number) {
                return ((Number) value).doubleValue();
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                // 支持科学计数法
                return new BigDecimal(valueStr.trim()).doubleValue();
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为double<br>
         * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Double toDouble(Object value) {
            return toDouble(value, null);
        }
    
        /**
         * 转换为Float<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Float toFloat(Object value, Float defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Float) {
                return (Float) value;
            }
            if (value instanceof Number) {
                return ((Number) value).floatValue();
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return Float.parseFloat(valueStr.trim());
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为Float<br>
         * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Float toFloat(Object value) {
            return toFloat(value, null);
        }
    
        /**
         * 转换为boolean<br>
         * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static Boolean toBool(Object value, Boolean defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof Boolean) {
                return (Boolean) value;
            }
            String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            valueStr = valueStr.trim().toLowerCase();
            switch (valueStr) {
                case "true":
                    return true;
                case "false":
                    return false;
                case "yes":
                    return true;
                case "ok":
                    return true;
                case "no":
                    return false;
                case "1":
                    return true;
                case "0":
                    return false;
                default:
                    return defaultValue;
            }
        }
    
        /**
         * 转换为boolean<br>
         * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static Boolean toBool(Object value) {
            return toBool(value, null);
        }
    
        /**
         * 转换为Enum对象<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         *
         * @param clazz        Enum的Class
         * @param value        值
         * @param defaultValue 默认值
         * @return Enum
         */
        public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (clazz.isAssignableFrom(value.getClass())) {
                @SuppressWarnings("unchecked")
                E myE = (E) value;
                return myE;
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return Enum.valueOf(clazz, valueStr);
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为Enum对象<br>
         * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
         *
         * @param clazz Enum的Class
         * @param value 值
         * @return Enum
         */
        public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {
            return toEnum(clazz, value, null);
        }
    
        /**
         * 转换为BigInteger<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static BigInteger toBigInteger(Object value, BigInteger defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof BigInteger) {
                return (BigInteger) value;
            }
            if (value instanceof Long) {
                return BigInteger.valueOf((Long) value);
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return new BigInteger(valueStr);
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为BigInteger<br>
         * 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static BigInteger toBigInteger(Object value) {
            return toBigInteger(value, null);
        }
    
        /**
         * 转换为BigDecimal<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value        被转换的值
         * @param defaultValue 转换错误时的默认值
         * @return 结果
         */
        public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) {
            if (value == null) {
                return defaultValue;
            }
            if (value instanceof BigDecimal) {
                return (BigDecimal) value;
            }
            if (value instanceof Long) {
                return new BigDecimal((Long) value);
            }
            if (value instanceof Double) {
                return new BigDecimal((Double) value);
            }
            if (value instanceof Integer) {
                return new BigDecimal((Integer) value);
            }
            final String valueStr = toStr(value, null);
            if (StringUtils.isEmpty(valueStr)) {
                return defaultValue;
            }
            try {
                return new BigDecimal(valueStr);
            } catch (Exception e) {
                return defaultValue;
            }
        }
    
        /**
         * 转换为BigDecimal<br>
         * 如果给定的值为空,或者转换失败,返回默认值<br>
         * 转换失败不会报错
         *
         * @param value 被转换的值
         * @return 结果
         */
        public static BigDecimal toBigDecimal(Object value) {
            return toBigDecimal(value, null);
        }
    
        /**
         * 将对象转为字符串<br>
         * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
         *
         * @param obj 对象
         * @return 字符串
         */
        public static String utf8Str(Object obj) {
            return str(obj, CharsetKit.CHARSET_UTF_8);
        }
    
        /**
         * 将对象转为字符串<br>
         * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
         *
         * @param obj         对象
         * @param charsetName 字符集
         * @return 字符串
         */
        public static String str(Object obj, String charsetName) {
            return str(obj, Charset.forName(charsetName));
        }
    
        /**
         * 将对象转为字符串<br>
         * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
         *
         * @param obj     对象
         * @param charset 字符集
         * @return 字符串
         */
        public static String str(Object obj, Charset charset) {
            if (null == obj) {
                return null;
            }
    
            if (obj instanceof String) {
                return (String) obj;
            } else if (obj instanceof byte[]) {
                return str((byte[]) obj, charset);
            } else if (obj instanceof Byte[]) {
                byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj);
                return str(bytes, charset);
            } else if (obj instanceof ByteBuffer) {
                return str((ByteBuffer) obj, charset);
            }
            return obj.toString();
        }
    
        /**
         * 将byte数组转为字符串
         *
         * @param bytes   byte数组
         * @param charset 字符集
         * @return 字符串
         */
        public static String str(byte[] bytes, String charset) {
            return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));
        }
    
        /**
         * 解码字节码
         *
         * @param data    字符串
         * @param charset 字符集,如果此字段为空,则解码的结果取决于平台
         * @return 解码后的字符串
         */
        public static String str(byte[] data, Charset charset) {
            if (data == null) {
                return null;
            }
    
            if (null == charset) {
                return new String(data);
            }
            return new String(data, charset);
        }
    
        /**
         * 将编码的byteBuffer数据转换为字符串
         *
         * @param data    数据
         * @param charset 字符集,如果为空使用当前系统字符集
         * @return 字符串
         */
        public static String str(ByteBuffer data, String charset) {
            if (data == null) {
                return null;
            }
    
            return str(data, Charset.forName(charset));
        }
    
        /**
         * 将编码的byteBuffer数据转换为字符串
         *
         * @param data    数据
         * @param charset 字符集,如果为空使用当前系统字符集
         * @return 字符串
         */
        public static String str(ByteBuffer data, Charset charset) {
            if (null == charset) {
                charset = Charset.defaultCharset();
            }
            return charset.decode(data).toString();
        }
    
        // ----------------------------------------------------------------------- 全角半角转换
    
        /**
         * 半角转全角
         *
         * @param input String.
         * @return 全角字符串.
         */
        public static String toSBC(String input) {
            return toSBC(input, null);
        }
    
        /**
         * 半角转全角
         *
         * @param input         String
         * @param notConvertSet 不替换的字符集合
         * @return 全角字符串.
         */
        public static String toSBC(String input, Set<Character> notConvertSet) {
            char c[] = input.toCharArray();
            for (int i = 0; i < c.length; i++) {
                if (null != notConvertSet && notConvertSet.contains(c[i])) {
                    // 跳过不替换的字符
                    continue;
                }
    
                if (c[i] == ' ') {
                    c[i] = '\u3000';
                } else if (c[i] < '\177') {
                    c[i] = (char) (c[i] + 65248);
    
                }
            }
            return new String(c);
        }
    
        /**
         * 全角转半角
         *
         * @param input String.
         * @return 半角字符串
         */
        public static String toDBC(String input) {
            return toDBC(input, null);
        }
    
        /**
         * 替换全角为半角
         *
         * @param text          文本
         * @param notConvertSet 不替换的字符集合
         * @return 替换后的字符
         */
        public static String toDBC(String text, Set<Character> notConvertSet) {
            char c[] = text.toCharArray();
            for (int i = 0; i < c.length; i++) {
                if (null != notConvertSet && notConvertSet.contains(c[i])) {
                    // 跳过不替换的字符
                    continue;
                }
    
                if (c[i] == '\u3000') {
                    c[i] = ' ';
                } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
                    c[i] = (char) (c[i] - 65248);
                }
            }
            String returnString = new String(c);
    
            return returnString;
        }
    
        /**
         * 数字金额大写转换 先写个完整的然后将如零拾替换成零
         *
         * @param n 数字
         * @return 中文大写数字
         */
        public static String digitUppercase(double n) {
            String[] fraction = {"角", "分"};
            String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
            String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};
    
            String head = n < 0 ? "负" : "";
            n = Math.abs(n);
    
            String s = "";
            for (int i = 0; i < fraction.length; i++) {
                s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
            }
            if (s.length() < 1) {
                s = "整";
            }
            int integerPart = (int) Math.floor(n);
    
            for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
                String p = "";
                for (int j = 0; j < unit[1].length && n > 0; j++) {
                    p = digit[integerPart % 10] + unit[1][j] + p;
                    integerPart = integerPart / 10;
                }
                s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
            }
            return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
        }
    }
    
    
    • 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
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554
    • 555
    • 556
    • 557
    • 558
    • 559
    • 560
    • 561
    • 562
    • 563
    • 564
    • 565
    • 566
    • 567
    • 568
    • 569
    • 570
    • 571
    • 572
    • 573
    • 574
    • 575
    • 576
    • 577
    • 578
    • 579
    • 580
    • 581
    • 582
    • 583
    • 584
    • 585
    • 586
    • 587
    • 588
    • 589
    • 590
    • 591
    • 592
    • 593
    • 594
    • 595
    • 596
    • 597
    • 598
    • 599
    • 600
    • 601
    • 602
    • 603
    • 604
    • 605
    • 606
    • 607
    • 608
    • 609
    • 610
    • 611
    • 612
    • 613
    • 614
    • 615
    • 616
    • 617
    • 618
    • 619
    • 620
    • 621
    • 622
    • 623
    • 624
    • 625
    • 626
    • 627
    • 628
    • 629
    • 630
    • 631
    • 632
    • 633
    • 634
    • 635
    • 636
    • 637
    • 638
    • 639
    • 640
    • 641
    • 642
    • 643
    • 644
    • 645
    • 646
    • 647
    • 648
    • 649
    • 650
    • 651
    • 652
    • 653
    • 654
    • 655
    • 656
    • 657
    • 658
    • 659
    • 660
    • 661
    • 662
    • 663
    • 664
    • 665
    • 666
    • 667
    • 668
    • 669
    • 670
    • 671
    • 672
    • 673
    • 674
    • 675
    • 676
    • 677
    • 678
    • 679
    • 680
    • 681
    • 682
    • 683
    • 684
    • 685
    • 686
    • 687
    • 688
    • 689
    • 690
    • 691
    • 692
    • 693
    • 694
    • 695
    • 696
    • 697
    • 698
    • 699
    • 700
    • 701
    • 702
    • 703
    • 704
    • 705
    • 706
    • 707
    • 708
    • 709
    • 710
    • 711
    • 712
    • 713
    • 714
    • 715
    • 716
    • 717
    • 718
    • 719
    • 720
    • 721
    • 722
    • 723
    • 724
    • 725
    • 726
    • 727
    • 728
    • 729
    • 730
    • 731
    • 732
    • 733
    • 734
    • 735
    • 736
    • 737
    • 738
    • 739
    • 740
    • 741
    • 742
    • 743
    • 744
    • 745
    • 746
    • 747
    • 748
    • 749
    • 750
    • 751
    • 752
    • 753
    • 754
    • 755
    • 756
    • 757
    • 758
    • 759
    • 760
    • 761
    • 762
    • 763
    • 764
    • 765
    • 766
    • 767
    • 768
    • 769
    • 770
    • 771
    • 772
    • 773
    • 774
    • 775
    • 776
    • 777
    • 778
    • 779
    • 780
    • 781
    • 782
    • 783
    • 784
    • 785
    • 786
    • 787
    • 788
    • 789
    • 790
    • 791
    • 792
    • 793
    • 794
    • 795
    • 796
    • 797
    • 798
    • 799
    • 800
    • 801
    • 802
    • 803
    • 804
    • 805
    • 806
    • 807
    • 808
    • 809
    • 810
    • 811
    • 812
    • 813
    • 814
    • 815
    • 816
    • 817
    • 818
    • 819
    • 820
    • 821
    • 822
    • 823
    • 824
    • 825
    • 826
    • 827
    • 828
    • 829
    • 830
    • 831
    • 832
    • 833
    • 834
    • 835
    • 836
    • 837
    • 838
    • 839
    • 840
    • 841
    • 842
    • 843
    • 844
    • 845
    • 846
    • 847
    • 848
    • 849
    • 850
    • 851
    • 852
    • 853
    • 854
    • 855

    StrFormatter

    package com.yymt.common.utils.text;
    
    
    import com.yymt.common.utils.StringUtils;
    
    /**
     * 字符串格式化
     *
     * @author ruoyi
     */
    public class StrFormatter {
        public static final String EMPTY_JSON = "{}";
        public static final char C_BACKSLASH = '\\';
        public static final char C_DELIM_START = '{';
        public static final char C_DELIM_END = '}';
    
        /**
         * 格式化字符串<br>
         * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
         * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
         * 例:<br>
         * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
         * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
         * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
         *
         * @param strPattern 字符串模板
         * @param argArray   参数列表
         * @return 结果
         */
        public static String format(final String strPattern, final Object... argArray) {
            if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) {
                return strPattern;
            }
            final int strPatternLength = strPattern.length();
    
            // 初始化定义好的长度以获得更好的性能
            StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
    
            int handledPosition = 0;
            int delimIndex;// 占位符所在位置
            for (int argIndex = 0; argIndex < argArray.length; argIndex++) {
                delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
                if (delimIndex == -1) {
                    if (handledPosition == 0) {
                        return strPattern;
                    } else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
                        sbuf.append(strPattern, handledPosition, strPatternLength);
                        return sbuf.toString();
                    }
                } else {
                    if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) {
                        if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) {
                            // 转义符之前还有一个转义符,占位符依旧有效
                            sbuf.append(strPattern, handledPosition, delimIndex - 1);
                            sbuf.append(Convert.utf8Str(argArray[argIndex]));
                            handledPosition = delimIndex + 2;
                        } else {
                            // 占位符被转义
                            argIndex--;
                            sbuf.append(strPattern, handledPosition, delimIndex - 1);
                            sbuf.append(C_DELIM_START);
                            handledPosition = delimIndex + 1;
                        }
                    } else {
                        // 正常占位符
                        sbuf.append(strPattern, handledPosition, delimIndex);
                        sbuf.append(Convert.utf8Str(argArray[argIndex]));
                        handledPosition = delimIndex + 2;
                    }
                }
            }
            // 加入最后一个占位符后所有的字符
            sbuf.append(strPattern, handledPosition, strPattern.length());
    
            return sbuf.toString();
        }
    }
    
    
    • 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

    StringUtils.java

    package com.yymt.common.utils;
    
    import com.yymt.common.utils.text.Convert;
    import org.springframework.util.AntPathMatcher;
    
    import java.math.BigDecimal;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * 字符串工具类
     *
     * @author ruoyi
     */
    public class StringUtils extends org.apache.commons.lang3.StringUtils {
        /**
         * 空字符串
         */
        private static final String NULLSTR = "";
    
    
        /**
         * 下划线
         */
        private static final char SEPARATOR = '_';
    
        /**
         * 获取参数不为空值
         *
         * @param value defaultValue 要判断的value
         * @return value 返回值
         */
        public static <T> T nvl(T value, T defaultValue) {
            return value != null ? value : defaultValue;
        }
    
        /**
         * * 判断一个Collection是否为空, 包含List,Set,Queue
         *
         * @param coll 要判断的Collection
         * @return true:为空 false:非空
         */
        public static boolean isEmpty(Collection<?> coll) {
            return isNull(coll) || coll.isEmpty();
        }
    
        /**
         * * 判断一个Collection是否非空,包含List,Set,Queue
         *
         * @param coll 要判断的Collection
         * @return true:非空 false:空
         */
        public static boolean isNotEmpty(Collection<?> coll) {
            return !isEmpty(coll);
        }
    
        /**
         * * 判断一个对象数组是否为空
         *
         * @param objects 要判断的对象数组
         *                * @return true:为空 false:非空
         */
        public static boolean isEmpty(Object[] objects) {
            return isNull(objects) || (objects.length == 0);
        }
    
        /**
         * * 判断一个对象数组是否非空
         *
         * @param objects 要判断的对象数组
         * @return true:非空 false:空
         */
        public static boolean isNotEmpty(Object[] objects) {
            return !isEmpty(objects);
        }
    
        /**
         * * 判断一个Map是否为空
         *
         * @param map 要判断的Map
         * @return true:为空 false:非空
         */
        public static boolean isEmpty(Map<?, ?> map) {
            return isNull(map) || map.isEmpty();
        }
    
        /**
         * * 判断一个Map是否为空
         *
         * @param map 要判断的Map
         * @return true:非空 false:空
         */
        public static boolean isNotEmpty(Map<?, ?> map) {
            return !isEmpty(map);
        }
    
        /**
         * * 判断一个字符串是否为空串
         *
         * @param str String
         * @return true:为空 false:非空
         */
        public static boolean isEmpty(String str) {
            return isNull(str) || NULLSTR.equals(str.trim());
        }
    
        /**
         * * 判断一个字符串是否为非空串
         *
         * @param str String
         * @return true:非空串 false:空串
         */
        public static boolean isNotEmpty(String str) {
            return !isEmpty(str);
        }
    
        /**
         * * 判断一个对象是否为空
         *
         * @param object Object
         * @return true:为空 false:非空
         */
        public static boolean isNull(Object object) {
            return object == null;
        }
    
        /**
         * * 判断一个对象是否非空
         *
         * @param object Object
         * @return true:非空 false:空
         */
        public static boolean isNotNull(Object object) {
            return !isNull(object);
        }
    
        /**
         * * 判断一个对象是否是数组类型(Java基本型别的数组)
         *
         * @param object 对象
         * @return true:是数组 false:不是数组
         */
        public static boolean isArray(Object object) {
            return isNotNull(object) && object.getClass().isArray();
        }
    
        /**
         * 去空格
         */
        public static String trim(String str) {
            return (str == null ? "" : str.trim());
        }
    
        /**
         * 截取字符串
         *
         * @param str   字符串
         * @param start 开始
         * @return 结果
         */
        public static String substring(final String str, int start) {
            if (str == null) {
                return NULLSTR;
            }
    
            if (start < 0) {
                start = str.length() + start;
            }
    
            if (start < 0) {
                start = 0;
            }
            if (start > str.length()) {
                return NULLSTR;
            }
    
            return str.substring(start);
        }
    
        /**
         * 截取字符串
         *
         * @param str   字符串
         * @param start 开始
         * @param end   结束
         * @return 结果
         */
        public static String substring(final String str, int start, int end) {
            if (str == null) {
                return NULLSTR;
            }
    
            if (end < 0) {
                end = str.length() + end;
            }
            if (start < 0) {
                start = str.length() + start;
            }
    
            if (end > str.length()) {
                end = str.length();
            }
    
            if (start > end) {
                return NULLSTR;
            }
    
            if (start < 0) {
                start = 0;
            }
            if (end < 0) {
                end = 0;
            }
    
            return str.substring(start, end);
        }
    
        public static final String EMPTY_JSON = "{}";
        public static final char C_BACKSLASH = '\\';
        public static final char C_DELIM_START = '{';
        public static final char C_DELIM_END = '}';
        /**
         * 格式化文本, {} 表示占位符<br>
         * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
         * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
         * 例:<br>
         * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
         * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
         * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
         *
         * @param strPattern 文本模板,被替换的部分用 {} 表示
         * @param argArray   参数值
         * @return 格式化后的文本
         */
        public static String format(String strPattern, Object... argArray) {
            if (isEmpty(argArray) || isEmpty(strPattern)) {
                return strPattern;
            }
            if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
            {
                return strPattern;
            }
            final int strPatternLength = strPattern.length();
    
            // 初始化定义好的长度以获得更好的性能
            StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
    
            int handledPosition = 0;
            int delimIndex;// 占位符所在位置
            for (int argIndex = 0; argIndex < argArray.length; argIndex++)
            {
                delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
                if (delimIndex == -1)
                {
                    if (handledPosition == 0)
                    {
                        return strPattern;
                    }
                    else
                    { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
                        sbuf.append(strPattern, handledPosition, strPatternLength);
                        return sbuf.toString();
                    }
                }
                else
                {
                    if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
                    {
                        if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
                        {
                            // 转义符之前还有一个转义符,占位符依旧有效
                            sbuf.append(strPattern, handledPosition, delimIndex - 1);
                            sbuf.append(Convert.utf8Str(argArray[argIndex]));
                            handledPosition = delimIndex + 2;
                        }
                        else
                        {
                            // 占位符被转义
                            argIndex--;
                            sbuf.append(strPattern, handledPosition, delimIndex - 1);
                            sbuf.append(C_DELIM_START);
                            handledPosition = delimIndex + 1;
                        }
                    }
                    else
                    {
                        // 正常占位符
                        sbuf.append(strPattern, handledPosition, delimIndex);
                        sbuf.append(Convert.utf8Str(argArray[argIndex]));
                        handledPosition = delimIndex + 2;
                    }
                }
            }
            // 加入最后一个占位符后所有的字符
            sbuf.append(strPattern, handledPosition, strPattern.length());
    
            return sbuf.toString();
        }
    
        /**
         * 是否为http(s)://开头
         *
         * @param link 链接
         * @return 结果
         */
        public static boolean ishttp(String link) {
            return StringUtils.startsWithAny(link, com.yymt.common.constants.Constant.HTTP, com.yymt.common.constants.Constant.HTTPS);
        }
    
        /**
         * 字符串转set
         *
         * @param str 字符串
         * @param sep 分隔符
         * @return set集合
         */
        public static final Set<String> str2Set(String str, String sep) {
            return new HashSet<String>(str2List(str, sep, true, false));
        }
    
        /**
         * 字符串转list
         *
         * @param str         字符串
         * @param sep         分隔符
         * @param filterBlank 过滤纯空白
         * @param trim        去掉首尾空白
         * @return list集合
         */
        public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
            List<String> list = new ArrayList<String>();
            if (StringUtils.isEmpty(str)) {
                return list;
            }
    
            // 过滤空白字符串
            if (filterBlank && StringUtils.isBlank(str)) {
                return list;
            }
            String[] split = str.split(sep);
            for (String string : split) {
                if (filterBlank && StringUtils.isBlank(string)) {
                    continue;
                }
                if (trim) {
                    string = string.trim();
                }
                list.add(string);
            }
    
            return list;
        }
    
        /**
         * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
         *
         * @param cs                  指定字符串
         * @param searchCharSequences 需要检查的字符串数组
         * @return 是否包含任意一个字符串
         */
        public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
            if (isEmpty(cs) || isEmpty(searchCharSequences)) {
                return false;
            }
            for (CharSequence testStr : searchCharSequences) {
                if (containsIgnoreCase(cs, testStr)) {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 驼峰转下划线命名
         */
        public static String toUnderScoreCase(String str) {
            if (str == null) {
                return null;
            }
            StringBuilder sb = new StringBuilder();
            // 前置字符是否大写
            boolean preCharIsUpperCase = true;
            // 当前字符是否大写
            boolean curreCharIsUpperCase = true;
            // 下一字符是否大写
            boolean nexteCharIsUpperCase = true;
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (i > 0) {
                    preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
                } else {
                    preCharIsUpperCase = false;
                }
    
                curreCharIsUpperCase = Character.isUpperCase(c);
    
                if (i < (str.length() - 1)) {
                    nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
                }
    
                if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
                    sb.append(SEPARATOR);
                } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
                    sb.append(SEPARATOR);
                }
                sb.append(Character.toLowerCase(c));
            }
    
            return sb.toString();
        }
    
        /**
         * 是否包含字符串
         *
         * @param str  验证字符串
         * @param strs 字符串组
         * @return 包含返回true
         */
        public static boolean inStringIgnoreCase(String str, String... strs) {
            if (str != null && strs != null) {
                for (String s : strs) {
                    if (str.equalsIgnoreCase(trim(s))) {
                        return true;
                    }
                }
            }
            return false;
        }
    
        /**
         * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
         *
         * @param name 转换前的下划线大写方式命名的字符串
         * @return 转换后的驼峰式命名的字符串
         */
        public static String convertToCamelCase(String name) {
            StringBuilder result = new StringBuilder();
            // 快速检查
            if (name == null || name.isEmpty()) {
                // 没必要转换
                return "";
            } else if (!name.contains("_")) {
                // 不含下划线,仅将首字母大写
                return name.substring(0, 1).toUpperCase() + name.substring(1);
            }
            // 用下划线将原始字符串分割
            String[] camels = name.split("_");
            for (String camel : camels) {
                // 跳过原始字符串中开头、结尾的下换线或双重下划线
                if (camel.isEmpty()) {
                    continue;
                }
                // 首字母大写
                result.append(camel.substring(0, 1).toUpperCase());
                result.append(camel.substring(1).toLowerCase());
            }
            return result.toString();
        }
    
        /**
         * 驼峰式命名法 例如:user_name->userName
         */
        public static String toCamelCase(String s) {
            if (s == null) {
                return null;
            }
            s = s.toLowerCase();
            StringBuilder sb = new StringBuilder(s.length());
            boolean upperCase = false;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
    
                if (c == SEPARATOR) {
                    upperCase = true;
                } else if (upperCase) {
                    sb.append(Character.toUpperCase(c));
                    upperCase = false;
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
    
        /**
         * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
         *
         * @param str  指定字符串
         * @param strs 需要检查的字符串数组
         * @return 是否匹配
         */
        public static boolean matches(String str, List<String> strs) {
            if (isEmpty(str) || isEmpty(strs)) {
                return false;
            }
            for (String pattern : strs) {
                if (isMatch(pattern, str)) {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 判断url是否与规则配置:
         * ? 表示单个字符;
         * * 表示一层路径内的任意字符串,不可跨层级;
         * ** 表示任意层路径;
         *
         * @param pattern 匹配规则
         * @param url     需要匹配的url
         * @return
         */
        public static boolean isMatch(String pattern, String url) {
            AntPathMatcher matcher = new AntPathMatcher();
            return matcher.match(pattern, url);
        }
    
        @SuppressWarnings("unchecked")
        public static <T> T cast(Object obj) {
            return (T) obj;
        }
    
        /**
         * 格式化距离文本
         *
         * @param distance 距离 单位:米
         * @return
         */
        public static String formatDistanceTextDesc(Integer distance) {
            if (distance == null || distance <= 0) {
                return "";
            }
            if (distance >= 1000) {
                return new BigDecimal(distance).divide(new BigDecimal(1000)).setScale(1, BigDecimal.ROUND_HALF_UP).toString() + "公里";
            }
            return distance.intValue() + "米";
        }
    
        /**
         * 判断字符串中是否全是中文
         *
         * @param str 待校验字符串
         * @return 是否全是中文
         */
        public static boolean isAllChinese(String str) {
            if (str == null) { return false; }
            Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
            Matcher m = p.matcher(str);
            return m.matches();
        }
    }
    
    
    • 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
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554

    CharsetKit.java

    package com.yymt.common.utils.text;
    
    
    import com.yymt.common.utils.StringUtils;
    
    import java.nio.charset.Charset;
    import java.nio.charset.StandardCharsets;
    
    /**
     * 字符集工具类
     *
     * @author ruoyi
     */
    public class CharsetKit {
        /**
         * ISO-8859-1
         */
        public static final String ISO_8859_1 = "ISO-8859-1";
        /**
         * UTF-8
         */
        public static final String UTF_8 = "UTF-8";
        /**
         * GBK
         */
        public static final String GBK = "GBK";
    
        /**
         * ISO-8859-1
         */
        public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);
        /**
         * UTF-8
         */
        public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
        /**
         * GBK
         */
        public static final Charset CHARSET_GBK = Charset.forName(GBK);
    
        /**
         * 转换为Charset对象
         *
         * @param charset 字符集,为空则返回默认字符集
         * @return Charset
         */
        public static Charset charset(String charset) {
            return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
        }
    
        /**
         * 转换字符串的字符集编码
         *
         * @param source      字符串
         * @param srcCharset  源字符集,默认ISO-8859-1
         * @param destCharset 目标字符集,默认UTF-8
         * @return 转换后的字符集
         */
        public static String convert(String source, String srcCharset, String destCharset) {
            return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
        }
    
        /**
         * 转换字符串的字符集编码
         *
         * @param source      字符串
         * @param srcCharset  源字符集,默认ISO-8859-1
         * @param destCharset 目标字符集,默认UTF-8
         * @return 转换后的字符集
         */
        public static String convert(String source, Charset srcCharset, Charset destCharset) {
            if (null == srcCharset) {
                srcCharset = StandardCharsets.ISO_8859_1;
            }
    
            if (null == destCharset) {
                destCharset = StandardCharsets.UTF_8;
            }
    
            if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) {
                return source;
            }
            return new String(source.getBytes(srcCharset), destCharset);
        }
    
        /**
         * @return 系统字符集编码
         */
        public static String systemCharset() {
            return Charset.defaultCharset().name();
        }
    }
    
    
    • 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

    Constant.java

    package com.yymt.common.constants;
    
    /**
     * @Author:xielin
     * @Description:
     * @Date:2021/1/9 14:51
     * @Version: 1.0
     */
    public class Constant {
        /**
         * 数据有效
         */
        public static String DATA_VALID = "1";
        /**
         * 数据无效
         */
        public static String DATA_INVALID = "0";
    
        /**
         * UTF-8 字符集
         */
        public static final String UTF8 = "UTF-8";
    
        /**
         * GBK 字符集
         */
        public static final String GBK = "GBK";
    
        /**
         * http请求
         */
        public static final String HTTP = "http://";
    
        /**
         * https请求
         */
        public static final String HTTPS = "https://";
    
        /**
         * 防重提交 redis key
         */
        public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";
    
    }
    
    
    • 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
  • 相关阅读:
    C++实现电话号码的字母组合--Leetcood(17)
    SpringBoot
    环形单链表问题
    C++ Reference: Standard C++ Library reference: C Library: cwchar: fwprintf
    ES6中 async 函数、await表达式 的基本用法
    【牛客 - 剑指offer】JZ8 二叉树的下一个结点 Java实现
    25-Java 单元测试&&日志 详解
    【C++面向对象侯捷下】2.转换函数 | 3.non-explicit-one-argument ctor
    Mac安装Mysql,并启动
    XHR level2的新功能
  • 原文地址:https://blog.csdn.net/weixin_45168162/article/details/125434141