JAVA项目工具类AND常用辅助类


API工具类
我就是要重复造轮子

1.静态方法中获取spring容器管理对象示例

静态方法中无法获取靠@Autowired或者@Value等注解注释的类成员属性对象(原理:静态方法排象),只能靠new,导致此类对象用@Autowired或者@Value等注解注释的属性为空值。

工具代码:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.Map;

/**
 * @author LifeLikeSummerFlowers
 * 在静态方法中获取spring容器管理对象
 * Component注解让项目在启动项目时加载这个类,该类继承自ApplicationContextAware,如果重写setApplicationContext方法,就可以获取到Spring容器对象
 */
@Component
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (BeanUtil.applicationContext == null) {
            BeanUtil.applicationContext = applicationContext;
        }
    }


    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }


    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }


    public static String getProperty(String name) {
        Environment environment = applicationContext.getEnvironment();
        return environment.getProperty(name);
    }


    public static <T> Map<String, T> getBeansByType(Class<T> clazz) {
        return getApplicationContext().getBeansOfType(clazz);
    }
}


样板使用

public static APIMonitorInfo getApiMonitor(SimpleUserInfo userInfo, String bssId, String bizTime, String handleTime,
                                               String apiType, String apiCode, String apiName, String states,
                                               String resultCode, String resultMessage, String clientIp,
                                               String remark1, String remark2){
//      APIMonitorInfo apiMonitorInfo= new APIMonitorInfo();
        APIMonitorInfo apiMonitorInfo = BeanUtil.getBean(APIMonitorInfo.class);
        if(userInfo != null){
            apiMonitorInfo.setUserMobile(userInfo.getUserMobile());
            apiMonitorInfo.setProvinceCode(userInfo.getProvinceCode());
            apiMonitorInfo.setCityCode(userInfo.getCityCode());
            apiMonitorInfo.setVersion(userInfo.getVersion());
            apiMonitorInfo.setApplicationChannel(userInfo.getApplicationChannel());
        }
        if(StringUtils.isBlank(bssId)){
            bssId = (userInfo != null ? userInfo.getUserMobile() : "00000000000") + "_"+bizTime+"_"+ RandomStringUtils.randomNumeric(4);
        }
        apiMonitorInfo.setBssId(bssId);
        apiMonitorInfo.setBizTime(bizTime);
        apiMonitorInfo.setHandleTime(handleTime);
        apiMonitorInfo.setApiType(apiType);
        apiMonitorInfo.setApiCode(apiCode);
        apiMonitorInfo.setApiName(apiName);
        apiMonitorInfo.setStates(states);
        apiMonitorInfo.setResultCode(resultCode);
        apiMonitorInfo.setResultMessage(resultMessage);
        apiMonitorInfo.setClientIp(clientIp);
        apiMonitorInfo.setRemark1(remark1);
        apiMonitorInfo.setRemark2(remark2);
        return apiMonitorInfo;
    }

2.常用JSON和对象互转

需求:日常经常各种JSON和对象的互转。稍微不注意,就出现各种问题。

导包

      <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.47</version>
       </dependency>

使用

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
1.对象转JSON
String data= JSON.toJsonString(obj)
2.JSON转对象
Obj obj = JSON.parseObject(data,Obj.class);
3.JSON转JSON对象(key-value结构)
JSONObject jsonObject = JSONObject.parseObject(data);
4.JSON转数组(示例Map数组)
List<Map> dataList =JSONObject.parseArray(data,Map.class);

JsonUtil

package cn.tedu.web.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtil {
    private static ObjectMapper mapper;
    private static JsonInclude.Include DEFAULT_PROPERTY_INCLUSION = JsonInclude.Include.NON_DEFAULT;
    private static boolean IS_ENABLE_INDENT_OUTPUT = false;
    private static String CSV_DEFAULT_COLUMN_SEPARATOR = ",";
    static {
        try {
            initMapper();
            configPropertyInclusion();
            configIndentOutput();
            configCommon();
        } catch (Exception e) {
            log.error("jackson config error", e);
        }
    }

    private static void initMapper() {
        mapper = new ObjectMapper();
    }

    private static void configCommon() {
        config(mapper);
    }

    private static void configPropertyInclusion() {
        mapper.setSerializationInclusion(DEFAULT_PROPERTY_INCLUSION);
    }

    private static void configIndentOutput() {
        mapper.configure(SerializationFeature.INDENT_OUTPUT, IS_ENABLE_INDENT_OUTPUT);
    }

    private static void config(ObjectMapper objectMapper) {
        objectMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        objectMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
        objectMapper.enable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
        objectMapper.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
        objectMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
        objectMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        objectMapper.registerModule(new ParameterNamesModule());
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(new GuavaModule());
    }
    public static void setSerializationInclusion(JsonInclude.Include inclusion) {
        DEFAULT_PROPERTY_INCLUSION = inclusion;
        configPropertyInclusion();
    }

    public static void setIndentOutput(boolean isEnable) {
        IS_ENABLE_INDENT_OUTPUT = isEnable;
        configIndentOutput();
    }

    public static <V> V from(URL url, Class<V> c) {
        try {
            return mapper.readValue(url, c);
        } catch (IOException e) {
            log.error("jackson from error, url: {}, type: {}", url.getPath(), c, e);
            return null;
        }
    }

    public static <V> V from(InputStream inputStream, Class<V> c) {
        try {
            return mapper.readValue(inputStream, c);
        } catch (IOException e) {
            log.error("jackson from error, type: {}", c, e);
            return null;
        }
    }

    public static <V> V from(File file, Class<V> c) {
        try {
            return mapper.readValue(file, c);
        } catch (IOException e) {
            log.error("jackson from error, file path: {}, type: {}", file.getPath(), c, e);
            return null;
        }
    }

    public static <V> V from(Object jsonObj, Class<V> c) {
        try {
            return mapper.readValue(jsonObj.toString(), c);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", jsonObj.toString(), c, e);
            return null;
        }
    }

    public static <V> V from(String json, Class<V> c) {
        try {
            return mapper.readValue(json, c);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", json, c, e);
            return null;
        }
    }

    public static <V> V from(URL url, TypeReference<V> type) {
        try {
            return mapper.readValue(url, type);
        } catch (IOException e) {
            log.error("jackson from error, url: {}, type: {}", url.getPath(), type, e);
            return null;
        }
    }

    public static <V> V from(InputStream inputStream, TypeReference<V> type) {
        try {
            return mapper.readValue(inputStream, type);
        } catch (IOException e) {
            log.error("jackson from error, type: {}", type, e);
            return null;
        }
    }

    public static <V> V from(File file, TypeReference<V> type) {
        try {
            return mapper.readValue(file, type);
        } catch (IOException e) {
            log.error("jackson from error, file path: {}, type: {}", file.getPath(), type, e);
            return null;
        }
    }

    public static <V> V from(Object jsonObj, TypeReference<V> type) {
        try {
            return mapper.readValue(jsonObj.toString(), type);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", jsonObj.toString(), type, e);
            return null;
        }
    }

    public static <V> V from(String json, TypeReference<V> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            log.error("jackson from error, json: {}, type: {}", json, type, e);
            return null;
        }
    }

    public static <V> String to(List<V> list) {
        try {
            return mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("jackson to error, obj: {}", list, e);
            return null;
        }
    }

    public static <V> String to(V v) {
        try {
            return mapper.writeValueAsString(v);
        } catch (JsonProcessingException e) {
            log.error("jackson to error, obj: {}", v, e);
            return null;
        }
    }

    public static <V> void toFile(String path, List<V> list) {
        try (Writer writer = new FileWriter(new File(path), true)) {
            mapper.writer().writeValues(writer).writeAll(list);
            writer.flush();
        } catch (Exception e) {
            log.error("jackson to file error, path: {}, list: {}", path, list, e);
        }
    }

    public static <V> void toFile(String path, V v) {
        try (Writer writer = new FileWriter(new File(path), true)) {
            mapper.writer().writeValues(writer).write(v);
            writer.flush();
        } catch (Exception e) {
            log.error("jackson to file error, path: {}, obj: {}", path, v, e);
        }
    }

    public static String getString(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).toString();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get string error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static Integer getInt(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).intValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get int error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static Long getLong(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).longValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get long error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static Double getDouble(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).doubleValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get double error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static BigInteger getBigInteger(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return new BigInteger(String.valueOf(0.00));
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).bigIntegerValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get biginteger error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static BigDecimal getBigDecimal(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).decimalValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get bigdecimal error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static boolean getBoolean(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return false;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).booleanValue();
            } else {
                return false;
            }
        } catch (IOException e) {
            log.error("jackson get boolean error, json: {}, key: {}", json, key, e);
            return false;
        }
    }

    public static byte[] getByte(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            JsonNode node = mapper.readTree(json);
            if (null != node) {
                return node.get(key).binaryValue();
            } else {
                return null;
            }
        } catch (IOException e) {
            log.error("jackson get byte error, json: {}, key: {}", json, key, e);
            return null;
        }
    }

    public static <T> ArrayList<T> getList(String json, String key) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        String string = getString(json, key);
        return from(string, new TypeReference<ArrayList<T>>() {});
    }

    public static <T> String add(String json, String key, T value) {
        try {
            JsonNode node = mapper.readTree(json);
            add(node, key, value);
            return node.toString();
        } catch (IOException e) {
            log.error("jackson add error, json: {}, key: {}, value: {}", json, key, value, e);
            return json;
        }
    }

    private static <T> void add(JsonNode jsonNode, String key, T value) {
        if (value instanceof String) {
            ((ObjectNode) jsonNode).put(key, (String) value);
        } else if (value instanceof Short) {
            ((ObjectNode) jsonNode).put(key, (Short) value);
        } else if (value instanceof Integer) {
            ((ObjectNode) jsonNode).put(key, (Integer) value);
        } else if (value instanceof Long) {
            ((ObjectNode) jsonNode).put(key, (Long) value);
        } else if (value instanceof Float) {
            ((ObjectNode) jsonNode).put(key, (Float) value);
        } else if (value instanceof Double) {
            ((ObjectNode) jsonNode).put(key, (Double) value);
        } else if (value instanceof BigDecimal) {
            ((ObjectNode) jsonNode).put(key, (BigDecimal) value);
        } else if (value instanceof BigInteger) {
            ((ObjectNode) jsonNode).put(key, (BigInteger) value);
        } else if (value instanceof Boolean) {
            ((ObjectNode) jsonNode).put(key, (Boolean) value);
        } else if (value instanceof byte[]) {
            ((ObjectNode) jsonNode).put(key, (byte[]) value);
        } else {
            ((ObjectNode) jsonNode).put(key, to(value));
        }
    }

    public static String remove(String json, String key) {
        try {
            JsonNode node = mapper.readTree(json);
            ((ObjectNode) node).remove(key);
            return node.toString();
        } catch (IOException e) {
            log.error("jackson remove error, json: {}, key: {}", json, key, e);
            return json;
        }
    }

    public static <T> String update(String json, String key, T value) {
        try {
            JsonNode node = mapper.readTree(json);
            ((ObjectNode) node).remove(key);
            add(node, key, value);
            return node.toString();
        } catch (IOException e) {
            log.error("jackson update error, json: {}, key: {}, value: {}", json, key, value, e);
            return json;
        }
    }

    public static String format(String json) {
        try {
            JsonNode node = mapper.readTree(json);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
        } catch (IOException e) {
            log.error("jackson format json error, json: {}", json, e);
            return json;
        }
    }

    public static boolean isJson(String json) {
        try {
            mapper.readTree(json);
            return true;
        } catch (Exception e) {
            log.error("jackson check json error, json: {}", json, e);
            return false;
        }
    }

    private static InputStream getResourceStream(String name) {
        return JsonUtil.class.getClassLoader().getResourceAsStream(name);
    }

    private static InputStreamReader getResourceReader(InputStream inputStream) {
        if (null == inputStream) {
            return null;
        }
        return new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    }
}

  • 轻量版
package com.utils;
 
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
/**
 * json转换工具类
 */
public class JsonUtils {
 
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
 
    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
    }
    
}

3.常用Cookie工具类

cookie作为保存浏览器与服务器之间状态信息的桥梁,在web开发中是必不可少的存在。以下是增删查的工具类
代码示例

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookiesUtil {

    /**
     * 写入cookies
     * @param key
     * @param descMobileAndPwdStr
     * @param response
     */
    public static void addCookies(String key, String descMobileAndPwdStr, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, descMobileAndPwdStr);
        cookie.setDomain("client.xxx.com");
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

    public static void addCookiesLuckDraw(String key, String descMobileAndPwdStr,
			HttpServletResponse response) {
		Cookie cookie = new Cookie(key, descMobileAndPwdStr);
		cookie.setPath("/");
		cookie.setMaxAge(-1);
		response.addCookie(cookie);
	}

    /**
     * 得到cookies
     * @param key
     * @param request
     * @return
     */
  	public static String getCookie(HttpServletRequest request, String name) {
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					value = cookie.getValue();
					break;
				}
			}
		}
		return value;
	}

    public static void delCookies(String key, HttpServletResponse response, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        try {
            for (int i = 0; i < cookies.length; i++) {
                Cookie c = cookies[i];
                if (key.equalsIgnoreCase(c.getName())) {
                    c.setMaxAge(0);
                    //根据你创建cookie的路径进行填写
                    c.setPath("/");
                    response.addCookie(c);
                }
            }
        } catch (Exception ex) {
        }
    }
}

    public static void clearCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
        String domain = "xxx.com";
        Cookie[] ck = request.getCookies();
        if (ck != null && ck.length > 0) {
            for (int i = 0; i < ck.length; i++) {
                if (ck[i].getName().equals(cookieName)) {
                    ck[i].setMaxAge(0);
                    ck[i].setPath("/");
                    ck[i].setDomain(domain);
                    response.addCookie(ck[i]);
                    break;
                }
            }
        }
    }

用法示例

//获取cookie中的值
String token = CookiesUtil.getCookiseValue("token", request);

4.Controller返回值类

一般返回都是JSON串,但是在各种场景下返回的值包含的内容不一致。

示例1

package cn.tedu.web.util;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class JsonResult<T> {
	/** 成功 */
	public static final int SUCCESS = 200;

	/** 没有登录 */
	public static final int NOT_LOGIN = 400;

	/** 发生异常 */
	public static final int EXCEPTION = 401;

	/** 系统错误 */
	public static final int SYS_ERROR = 402;

	/** 参数错误 */
	public static final int PARAMS_ERROR = 403;

	/** 不支持或已经废弃 */
	public static final int NOT_SUPPORTED = 410;

	/** AuthCode错误 */
	public static final int INVALID_AUTHCODE = 444;

	/** 太频繁的调用 */
	public static final int TOO_FREQUENT = 445;

	/** 未知的错误 */
	public static final int UNKNOWN_ERROR = 499;
	
	private int code;
	private String msg;
	private T data;
	
	

	public static JsonResult build() {
		return new JsonResult();
	}
	public static JsonResult build(int code) {
		return new JsonResult().code(code);
	}
	public static JsonResult build(int code, String msg) {
		return new JsonResult<String>().code(code).msg(msg);
	}
	public static <T> JsonResult<T> build(int code, T data) {
		return new JsonResult<T>().code(code).data(data);
	}
	public static <T> JsonResult<T> build(int code, String msg, T data) {
		return new JsonResult<T>().code(code).msg(msg).data(data);
	}
	
	public JsonResult<T> code(int code) {
		this.code = code;
		return this;
	}
	public JsonResult<T> msg(String msg) {
		this.msg = msg;
		return this;
	}
	public JsonResult<T> data(T data) {
		this.data = data;
		return this;
	}
	
	
	public static JsonResult ok() {
		return build(SUCCESS);
	}
	public static JsonResult ok(String msg) {
		return build(SUCCESS, msg);
	}
	public static <T> JsonResult<T> ok(T data) {
		return build(SUCCESS, data);
	}
	public static JsonResult err() {
		return build(EXCEPTION);
	}
	public static JsonResult err(String msg) {
		return build(EXCEPTION, msg);
	}
	
	@Override
	public String toString() {
		return JsonUtil.to(this);
	}
}

示例2

import com.common.util.DateUtil;
import com.common.util.UUID;
import com..APIConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


public class APIResult {
	protected Logger log = LoggerFactory.getLogger(APIResult.class);
	
	public String bizid;//接口标识
	public String reqsn;//原请求发起交易流水
	public String ressn;//请求返回交易流水
	public String restime;//请求返回时间戳(yyyyMMddHHmmssSSS)
	public String status;//请求状态
	public String code;//请求状态编码
	public String msg;//请求状态说明
	public String stype;//安全协议类型
	public String skey;//RSA(AESKey)
	public Object resdata;//响应JSON
	
	/** 默认正常返回 */
	public APIResult(Object object){
		init(null, null, null, null, null, null, null, null, null, object);
	}
	
	/** 
	 * 接口正常返回<br />
	 * @param code 业务响应码,必填
	 * @param msg 业务状态说明,可选
	 */
	public APIResult(String code, String msg){
		init(null, null, null, null, null, code, msg, null, null, null);
	}
	
	/** 
	 * 接口正常返回<br />
	 * @param code 业务响应码,必填
	 * @param msg 业务状态说明,可选
	 * @param object 返回对象,可选
	 */
	public APIResult(String code, String msg, Object object){
		init(null, null, null, null, null, code, msg, null, null, object);
	}

	public APIResult(String code, String msg, Object object,String count){
		init(null, null, null, null, null, code, msg, null, count, object);
	}
	/** 
	 * 接口正常返回<br />
	 * @param code 业务响应码,必填
	 * @param msg 业务状态说明,可选
	 * @param object 返回对象,可选
	 */
	public APIResult(Integer code, String msg, Object object){
		init(null, null, null, null, null, (code + ""), msg, null, null, object);
	}

	/** 
	 * 自定义接口状态返回<br />
	 * @param apiStatus 接口响应状态,可选 默认成功
	 * @param code 业务响应码,必填
	 * @param msg 业务状态说明,可选
	 * @param object 返回对象,可选
	 */
	public APIResult(APIStatus apiStatus, String code, String msg, Object object){
		init(apiStatus, null, null, null, null, code, msg, null, null, object);
	}
	
	/** 
	 * 自定义接口编号返回,默认接口响应成功<br />
	 * @param bizid 接口编号,必填
	 * @param code 业务响应码,必填
	 * @param msg 业务状态说明,可选
	 * @param object 返回对象,可选
	 */
	public APIResult(String bizid, String code, String msg, Object object){
		init(null, bizid, null, null, null, code, msg, null, null, object);
	}
	
	/** 
	 * 自定义接口返回,默认接口响应成功<br />
	 * @param apiStatus	接口状态,可选 默认成功
	 * @param bizid	接口标识
	 * @param reqsn	原请求发起交易流水
	 * @param ressn 请求返回交易流水
	 * @param stype 安全协议类型
	 * @param skey RSA(AESKey)
	 */
	public APIResult(APIStatus apiStatus, String bizid, String reqsn, String ressn, String restime, String stype, String skey, Object resdata){
		init(apiStatus, bizid, reqsn, ressn, restime, null, null, stype, skey, resdata);
	}
	
	/** 
	 * 自定义接口返回,默认接口响应成功<br />
	 * @param apiStatus	接口状态,可选 默认成功
	 * @param bizid	接口标识
	 * @param reqsn	原请求发起交易流水
	 * @param ressn 请求返回交易流水
	 * @param restime 请求返回时间戳
	 * @param code 请求状态编码
	 * @param msg 请求状态说明
	 * @param stype 安全协议类型
	 * @param skey RSA(AESKey)
	 */
	public APIResult(APIStatus apiStatus, String bizid, String reqsn, String ressn, String restime, String code, String msg, String stype, String skey, Object resdata){
		init(apiStatus, bizid, reqsn, ressn, restime, code, msg, stype, skey, resdata);
	}
	
	/**
	 * 初始化设置
	 * @author zhangliqing
	 * @creationDate. 2018年4月17日 上午12:14:02 
	 * @param apiStatus	接口状态,可选 默认成功
	 * @param bizid	接口标识
	 * @param reqsn	原请求发起交易流水
	 * @param ressn 请求返回交易流水
	 * @param restime 请求返回时间戳
	 * @param code 请求状态编码
	 * @param msg 请求状态说明
	 * @param stype 安全协议类型
	 * @param skey RSA(AESKey)
	 * @param resdata 响应JSON
	 */
	private void init(APIStatus apiStatus,String bizid,String reqsn, String ressn, String restime,String code,String msg,String stype,String skey,Object resdata){

		//默认接口状态是正常
		if (apiStatus == null) {
			apiStatus = APIStatus.SUCCESS;
		}
		status = apiStatus.getValue();
		//默认使用请求中的安全协议类型
		if(stype == null){
			stype = getReqAttribute(APIConstants.HTTP_REQ_PARAM_STYPE) + "";
		}
		//若响应使用加密,对响应JSON进行加密处理
		if(!StringUtils.isEmpty(stype) && "1".equals(stype)){
			//TODO 进行加密处理
		}else{
			stype = "0";
		}
		
		//默认使用请求中携带的接口标识
		if(StringUtils.isEmpty(bizid)){
			bizid = getReqAttribute(APIConstants.HTTP_REQ_PARAM_BIZID) + "";
		}
		//默认使用请求中携带的请求流水
		if(StringUtils.isEmpty(reqsn)){
			reqsn = getReqAttribute(APIConstants.HTTP_REQ_PARAM_REQSN) + "";
		}
		//默认使自动生成响应流水
		if(StringUtils.isEmpty(ressn)){
			ressn = UUID.getUUID();
		}
		//默认使自动生成响应时间戳
		if(StringUtils.isEmpty(restime)){
			restime = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
		}
		if(StringUtils.isEmpty(msg)){
			msg = "";
		}
		if(StringUtils.isEmpty(code)){
			code = "";
		}
		if(StringUtils.isEmpty(skey)){
			skey = "";
		}
		if(StringUtils.isEmpty(stype)){
			stype = "0";
		}
		if(resdata == null){
			resdata = "";
		}
		
		this.bizid = bizid;
		this.reqsn = reqsn;
		this.ressn = ressn;
		this.restime = restime;
		this.code = code;
		this.msg = msg;
		this.stype = stype;
		this.skey = skey;
		this.resdata = resdata;
	}
	
	//获取请求中存储的参数
	private Object getReqAttribute(String reqAttrName){
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		if(servletRequestAttributes == null) return "";
		HttpServletRequest request = servletRequestAttributes.getRequest();
		if(request == null) return "";
		return request.getAttribute(reqAttrName);
	}

	
	
	public String getBizid() {
		return bizid;
	}

	public void setBizid(String bizid) {
		this.bizid = bizid;
	}

	public String getReqsn() {
		return reqsn;
	}

	public void setReqsn(String reqsn) {
		this.reqsn = reqsn;
	}

	public String getRessn() {
		return ressn;
	}

	public void setRessn(String ressn) {
		this.ressn = ressn;
	}

	public String getRestime() {
		return restime;
	}

	public void setRestime(String restime) {
		this.restime = restime;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getStype() {
		return stype;
	}

	public void setStype(String stype) {
		this.stype = stype;
	}

	public String getSkey() {
		return skey;
	}

	public void setSkey(String skey) {
		this.skey = skey;
	}


	public Object getResdata() {
		return resdata;
	}


	public void setResdata(Object resdata) {
		this.resdata = resdata;
	}
}

5.过滤器配置样板AND拦截器配置样板

过滤器经常用来做路径拦截或者逻辑增加功能,底层是AOP实现。重写doFilter方法,在该方法完成业务。 chain.doFilter()则放行。return则实行拦截,一般都是跳登录页面。

  • 配置类
@Configuration
public class FilterConfig {

    @Autowired
    private EscapeSensitiveWordFilter escapeSensitiveWordFilter;

    /**
     * 特殊符号过滤
     */
    @Bean
    public FilterRegistrationBean EscapeSensitiveWordFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(escapeSensitiveWordFilter);
        registration.addUrlPatterns("/xxx/api/*");
        registration.addUrlPatterns("/xxx/show/*");
        registration.addUrlPatterns("/xxx/newShow/*");
        registration.addUrlPatterns("/xxx/activity/*");
        registration.addUrlPatterns("/xxx/pointGame/*");
        registration.addUrlPatterns("/xxx/directionalScore/*");
        registration.setName("escapeSensitiveWordFilter");
        registration.addInitParameter("sensitiveWords","(,),<,>,*,',+,select ,insert ,update ,delete , and , or , join , union ,truncate ,drop,alert,script, onclick, expression , iframe ,../../../../,./,sleep");

        //例外的地址,即用户不登录也可以请求
        List<String> excludePathPatternsList = new ArrayList<String>();
        //提交订单时忽略特殊字符--收货地址会有特殊字符的出现
        excludePathPatternsList.add("/xx");
        excludePathPatternsList.add("/xxx");
        StringBuffer excludeWordPatternsBuffer = new StringBuffer();
        for(String str:excludePathPatternsList) {
            excludeWordPatternsBuffer.append(str+",");
        }
        String excludeWordPatterns = excludeWordPatternsBuffer.toString().substring(0, excludeWordPatternsBuffer.toString().length()-1);
        registration.addInitParameter("excludeWordPatterns",excludeWordPatterns);

        //值越小,Filter越靠前。
        registration.setOrder(1);
        return registration;
    }
}

  • 过滤器
@Slf4j
@Component
public class EscapeSensitiveWordFilter implements Filter {

    private static String[] sensitiveWordsList = null;
    private List<String> excludeWordList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String sensitiveWords = filterConfig.getInitParameter("sensitiveWords");
        if(StringUtils.isNotBlank(sensitiveWords)){
            sensitiveWordsList = sensitiveWords.split(",");
        }
        String excludeWordPatterns = filterConfig.getInitParameter("excludeWordPatterns");
        if(StringUtils.isNotBlank(excludeWordPatterns)){
            excludeWordList = Arrays.asList(excludeWordPatterns.split(","));
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        log.info("特殊符号过滤器url:" + url);

        boolean filterFlag = false;
        if(excludeWordList != null){
            for (String str : excludeWordList) {
                if (url.indexOf(str) > 0) {
                    filterFlag = true;
                    break;
                }
            }
        }
        if (filterFlag){
            chain.doFilter(servletRequest, response);
        } else {
            TextValidTool mustTool = new TextValidTool(sensitiveWordsList);
            Map param = request.getParameterMap();
            log.info("特殊符号过滤器param:" + param);
            Iterator it = param.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry e = (Map.Entry) it.next();
                String[] value = (String[]) e.getValue();
                if (mustTool.hasEspecialChar(value)) {
                    log.info(url + ",敏感字符检测参数有敏感字符,禁止请求该资源.");
                    response.sendError(500);
                    return;
                }
            }
            chain.doFilter(servletRequest, response);
        }
    }

    @Override
    public void destroy() {
        log.info("特殊符号过滤器destory");
    }
}

二者区别:

在这里插入图片描述

spring的拦截器和servlet的过滤器有相似之处,都是AOP思想的体现,都可以实现权限检查,日志记录,不同的是:

适用范围不同:Filter是Servlet容器规定的,只能使用在servlet容器中,而拦截器的使用范围就大得多
使用的资源不同:拦截器是属于spring的一个组件,因此可以使用spring的所有资源,对象,如service对象,数据源,事务控制等,而过滤器就不行
深度不同:Filter还在servlet前后起作用。而拦截器能够深入到方法前后,异常抛出前后,因此拦截器具有更大的弹性,所有在spring框架中应该优先使用拦截器。
通过调试可以发现,拦截器的执行过程是在过滤器的doFilter中执行的,过滤器的初始化会在项目启动时执行。
在这里插入图片描述
  过滤器和拦截器的精确区别:拦截器是被包裹在过滤器之中的。

过滤器:
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("before...");
        chain.doFilter(request, response);
        System.out.println("after...");
    }
    
拦截器:
 @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }

①拦截器是基于java的反射机制的,而过滤器是基于函数回调。
  ②拦截器不依赖与servlet容器,过滤器依赖与servlet容器。
  ③拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。
  ④拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。
  ⑤在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。

⑥拦截器可以获取IOC容器中的各个bean,而过滤器就不行,这点很重要,在拦截器里注入一个service,可以调用业务逻辑。
  
在这里插入图片描述

  • 注册拦截器
    需要将拦截器注册到spring容器中,可以通过implements WebMvcConfigurer,覆盖其addInterceptors(InterceptorRegistry registry)方法。记得把Bean注册到Spring容器中,可以选择@Component 或者 @Configuration。
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
	// 多个拦截器组成一个拦截器链
    // addPathPatterns 用于添加拦截规则
    // excludePathPatterns 用户排除拦截 
	registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
    registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
	super.addInterceptors(registry);
}
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注意这里注册了两个拦截器。这两个拦截器的执行顺序和配置顺序有关系,
        //即先配置顺序就在前(感觉这样不太方便,但没有找到设置类似order的API)  
       	registry.addInterceptor(new InterceptorDemo2()).addPathPatterns("/**");
        registry.addInterceptor(new InterceptorDemo()).addPathPatterns("/**");
    }
 }

  • 实现拦截器
    实现拦截器可以通过继承HandlerInterceptorAdapter类。如果preHandle方法return true,则继续后续处理。
public class InterceptorDemo extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        System.out.println("前置拦截器1 preHandle: 请求的uri为:"+requestURL.toString());
        System.out.println("在请求处理之前进行调用(Controller方法调用之前)");
        return true;// 只有返回true才会继续向下执行,返回false取消当前请求
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作) ");
    }
}

6.全局异常处理类(SpringBoot环境)

全局异常处理经常作为最后一层的异常处理,对于不处理的异常进行通用的处置。一般重写自定义异常。
在这里插入图片描述

  • 异常枚举类
package com.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public enum ExceptionEnum {
    OK(200,"请求正常响应"),
    NOT_LOGIN(210,"用户未登录"),
    CHECK_FAILED(300,"参数错误"),
    ERROR(400,"非法的请求"),
    SERVER_FAILED(999,"网络错误,待会重试");
    private Integer code;
    private String msg;

}
  • 自定义异常示范
package com.exception;
import com.ExceptionEnum;

public class WebException extends RuntimeException {

    private final ExceptionEnum response;

    public WebException(ExceptionEnum response) {
        this.response = response;
    }
    public ExceptionEnum getResponse() {
        return response;
    }
}
  • 全局异常处理类
package com.exception;
import com.alibaba.fastjson.JSON;
import com.enums.ExceptionEnum;
import com.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class WebExceptionHandler {

    @ExceptionHandler(WebException.class)
    @ResponseBody
    public ResponseResult handleStudentException(HttpServletRequest request, WebException ex) {
        ResponseResult response;
        log.error("捕获自定义异常编码:{},响应消息:{}",ex.getResponse().getCode(),ex.getResponse().getMsg());
        response = ResponseResult.build(ex.getResponse().getCode(),ex.getResponse().getMsg());
        log.info("捕获自定义异常,响应页面:{}", JSON.toJSONString(response));
        return response;
    }
    
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult handleException(HttpServletRequest request, Exception ex) {
        ResponseResult response;
        log.error("捕获非自定义异常。exception error:",ex);
        response = ResponseResult.build(ExceptionEnum.SERVER_FAILED.getCode(), ExceptionEnum.SERVER_FAILED.getMsg());
        log.info("捕获非自定义异常,响应页面:{}", JSON.toJSONString(response));
        return response;
    }
}

7.唯一图片名(随机商品id)生成

  • 不想废话了,直接上代码
import java.util.Random;  
import java.util.Date;   
public class IDUtils { 
/**
图片名生成(生成时间+uuid)
UUID类:用唯一标识符 (UUID) 的类。 UUID 表示一个 128 位的值。
UUID(Universally Unique Identifier)全局唯一标识符,
是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。
按照开放软件基金会(OSF)制定的标准计算,用到了以太网卡地址、纳秒级时间、
芯片ID码和许多可能的数字。由以下几部分的组合:当前日期和时间(UUID的第
一个部分与时间有关,如果你在生成一个UUID之后,过几秒又生成一个UUID,则
第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,
从网卡获得,没有网卡以其他方式获得),UUID的唯一缺陷在于生成的结果串会比较
长。标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx (8-4-4-4-12),
其中每个 x 是 0-9 或 a-f 范围内的一个十六进制的数字;
*/
	public static String genImageName() {
		Date day = new Date();    
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		String time = df.format(day);
		UUID u = UUID.randomUUID();
		String str = time +":"+ u.toString + "jpg";
		return str;
	}
	
	/**
	 * 商品id生成
	 */
	public static long genItemId() {
		//取当前时间的长整形值包含毫秒
		long millis = System.currentTimeMillis();
		//加上两位随机数
		Random random = new Random();
		int end2 = random.nextInt(99);
		//如果不足两位前面补0
		String str = millis + String.format("%02d", end2);
		long id = new Long(str);
		return id;
	}
	/**
	*随机数生成(自控位数随机数,大可能会重复)
	*/
	Random rnd = new Random();  
	public String getRandomNumber(int digCount) {  
    	StringBuilder sb = new StringBuilder(digCount);  
    	for(int i=0; i < digCount; i++)  
        	sb.append((char)('0' + rnd.nextInt(10)));  
   		return sb.toString();  
	}  
	
	/**
	*随机数生成(自控位数随机数,基本不会重复)
	*/
    public static void getRandomNumber2(int digCoun){  
        long timeMill = System.CurrentTime; 
        Random rand = new Random(timeMill); 
        StringBuilder sb = new StringBuilder(digCount); 
        for(int i = 0; i < digCount; i++){  
           sb.append((char)('0' + rnd.nextInt(10)));  
    	return sb.toString();  
    }  
}

8.ftp上传下载工具类

package com.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
 

public class FtpUtil {
 
	/** 
	 * Description: 向FTP服务器上传文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param basePath FTP服务器基础目录
	 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
	 * @param filename 上传到FTP服务器上的文件名 
	 * @param input 输入流 
	 * @return 成功返回true,否则返回false 
	 */  
	public static boolean uploadFile(String host, int port, String username, String password, String basePath,
			String filePath, String filename, InputStream input) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);// 连接FTP服务器
			// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			//切换到上传目录
			if (!ftp.changeWorkingDirectory(basePath+filePath)) {
				//如果目录不存在创建目录
				String[] dirs = filePath.split("/");
				String tempPath = basePath;
				for (String dir : dirs) {
					if (null == dir || "".equals(dir)) continue;
					tempPath += "/" + dir;
					if (!ftp.changeWorkingDirectory(tempPath)) {
						if (!ftp.makeDirectory(tempPath)) {
							return result;
						} else {
							ftp.changeWorkingDirectory(tempPath);
						}
					}
				}
			}
			//设置上传文件的类型为二进制类型
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			//上传文件
			if (!ftp.storeFile(filename, input)) {
				return result;
			}
			input.close();
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	/** 
	 * Description: 从FTP服务器下载文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param remotePath FTP服务器上的相对路径 
	 * @param fileName 要下载的文件名 
	 * @param localPath 下载后保存到本地的路径 
	 * @return 
	 */  
	public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
			String fileName, String localPath) {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(host, port);
			// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + "/" + ff.getName());
 
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
 
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		try {  
	        FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));  
	        boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);  
	        System.out.println(flag);  
	    } catch (FileNotFoundException e) {  
	        e.printStackTrace();  
	    }  
	}
}

9.HttpClientUtils

  • HttpCLient介绍:
    在这里插入图片描述
package com.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class NewHttpCilentUtil {

    private static final CloseableHttpClient httpClient;

    public static final String CHARSET = "UTF-8";

    // 采用静态代码块,初始化超时时间配置,再根据配置生成默认httpClient对象
    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(8000).setSocketTimeout(8000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    public static String doGet(String url, Map<String, String> params) {
        return doGet(url, params, CHARSET);
    }


    public static String doPost(String url, Map<String, String> params){
        return doPost(url, params, CHARSET);
    }


    /**
     * HTTP Get 获取内容
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doGet(String url, Map<String, String> params, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String result = null;
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                // 将请求参数和url进行拼接
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            long start = System.currentTimeMillis();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            EntityUtils.consume(entity);
            response.close();
        } catch (Exception e) {
            log.error("GET请求异常",e);
        }
        return result;
    }

    /**
     * http Get请求,参数为一个对象
     * @param url
     * @param object    参数对象
     * @param charset
     * @return
     */
    public static String doGet(String url, Object object, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String result = null;
        try {
            if (object != null){
                List<NameValuePair> pairs = new ArrayList<>();
                for (Field field : object.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    Object value = field.get(object);
                    if (value != null){
                        pairs.add(new BasicNameValuePair(field.getName(),String.valueOf(value)));
                    }
                }
                // 将请求参数和url进行拼接
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            long start = System.currentTimeMillis();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            EntityUtils.consume(entity);
            response.close();
        } catch (Exception e) {
            log.error("GET请求异常",e);
        }
        return result;
    }

    /**
     * HTTP Post 获取内容
     * @param url 请求的url地址 ?之前的地址
     * @param params 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> params, String charset){
        if (StringUtils.isBlank(url)) {
            return null;
        }
        List<NameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
        }
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
            }

            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200 && statusCode != 302) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            EntityUtils.consume(entity);
            return result;
        }catch (Exception e){
            log.info("http-Post调用异常,",e);
            return null;
        }finally {
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    log.info("关闭响应异常",e);
                }
            }
        }
    }

    /**
     * HTTP Post 获取内容
     * @param url 请求的url地址 ?之前的地址
     * @param object 请求的参数
     * @param charset 编码格式
     * @return 页面内容
     *
     */
    public static String doPost(String url, Object object, String charset){
        if (StringUtils.isBlank(url)) {
            return null;
        }

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            List<NameValuePair> pairs = null;
            if (object != null){
                pairs = new ArrayList<>();
                for (Field field : object.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    Object value = field.get(object);
                    if (value != null){
                        pairs.add(new BasicNameValuePair(field.getName(),String.valueOf(value)));
                    }
                }
            }

            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
            }

            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200 && statusCode != 302) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, CHARSET);
            }
            EntityUtils.consume(entity);
            return result;
        }catch (Exception e){
            log.info("http-Post调用异常,",e);
            return null;
        }finally {
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    log.info("关闭响应异常",e);
                }
            }
        }
    }

    /**
     * 指定 JSON格式的ContentType 的post请求.
     * @param url
     * @param json
     * @param charset
     * @return
     */
    public static String doPost(String url, String json, String charset){
        if (StringUtils.isBlank(url)) {
            return null;
        }
        charset = StringUtils.isBlank(charset) ? "UTF-8" : charset;
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            if (StringUtils.isNotBlank(json)) {
                StringEntity stringEntity = new StringEntity(json,charset);
                stringEntity.setContentEncoding(charset);
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
            }
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 || statusCode == 400 || statusCode == 302) {
                HttpEntity entity = response.getEntity();
                String result = null;
                if (entity != null) {
                    result = EntityUtils.toString(entity, charset);
                }
                EntityUtils.consume(entity);
                return result;
            }else{
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
        }catch (Exception e){
            log.error("http-Post调用异常,",e);
            return null;
        }finally {
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭响应异常",e);
                }
            }
        }
    }

    public static String sendPost(String url, String json, String charset){
        if (StringUtils.isBlank(url)) {
            return null;
        }
        charset = StringUtils.isBlank(charset) ? "UTF-8" : charset;
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            if (StringUtils.isNotBlank(json)) {
                StringEntity stringEntity = new StringEntity(json);
                stringEntity.setContentEncoding(charset);
                stringEntity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(stringEntity);
            }
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 || statusCode == 400) {
                HttpEntity entity = response.getEntity();
                String result = null;
                if (entity != null) {
                    result = EntityUtils.toString(entity, charset);
                }
                EntityUtils.consume(entity);
                return result;
            }else{
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
        }catch (Exception e){
            log.error("http-Post调用异常,",e);
            return null;
        }finally {
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭响应异常",e);
                }
            }
        }
    }

    public static String sendPost(String urlParam, Map<String, String> params, String charset) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
        StringBuffer sbParams = new StringBuffer();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> e : params.entrySet()) {
                sbParams.append(e.getKey());
                sbParams.append("=");
                sbParams.append(e.getValue());
                sbParams.append("&");
            }
        }
        URLConnection con = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        try {
            URL realUrl = new URL(urlParam);
            // 打开和URL之间的连接
            con = realUrl.openConnection();
            // 设置通用的请求属性
            con.setRequestProperty("accept", "*/*");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            con.setDoOutput(true);
            con.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            osw = new OutputStreamWriter(con.getOutputStream(), charset);
            if (sbParams != null && sbParams.length() > 0) {
                // 发送请求参数
                osw.write(sbParams.substring(0, sbParams.length() - 1));
                // flush输出流的缓冲
                osw.flush();
            }
            // 定义BufferedReader输入流来读取URL的响应
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    osw = null;
                    throw new RuntimeException(e);
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

}

10用户敏感信息脱敏

    /**
     * 对用户的地址信息,姓名和省份证信息脱敏
     * @param userInfo
     * @return
     */
    public static UserInfo handleUserinfo(UserInfo userInfo){
        UserInfo user = new UserInfo();
        if(userInfo != null){
            BeanUtils.copyProperties(userInfo,user);
            try{
                String customName = user.getCustomName();
                String nikename = user.getNikename();
                String cert_num = user.getCert_num();
                if(StringUtils.isNotBlank(customName)){
                    user.setCustomName(customName.substring(0,1)+"*");
                }
                if(StringUtils.isNotBlank(nikename)){
                    user.setNikename(nikename.substring(0,1)+"*");
                }
                //身份证明为身份证号
                if(StringUtils.equals("02",user.getCert_type()) ||
                        StringUtils.equals("01",user.getCert_type())){
                    if(StringUtils.isNotBlank(cert_num)){
                        //15位省份证信息
                        if (cert_num.length() == 15) {
                            user.setCert_num(cert_num.substring(0,3)+"*********"+cert_num.substring(12));
                        }
                        //18位省份证信息
                        if (cert_num.length() == 18) {
                            user.setCert_num(cert_num.substring(0,3)+"************"+cert_num.substring(15));
                        }
                    }
                }
            }catch (Exception e){
                log.error("用户信息脱敏异常",e);
            }
        }
        return  user;
    }

11.加密解密

  • md5
package com.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import java.security.MessageDigest;


public class MD5Util {

	static Logger log = LoggerFactory.getLogger(MD5Util.class);

	/**
	 *
	 * @param str	需要加密的字符串
	 * @param isUpper 	字母大小写(false为默认小写,true为大写)
	 * @param bit 	加密的类型(16,32,64)
	 * @return
	 */
	public static String getMD5(String str, boolean isUpper, Integer bit) {
		String md5 = new String();
		try {
			// 创建加密对象
			MessageDigest md = MessageDigest.getInstance("md5");
			if (bit == 64) {
				BASE64Encoder bw = new BASE64Encoder();
				String bsB64 = bw.encode(md.digest(str.getBytes("utf-8")));
				md5 = bsB64;
			} else {
				// 计算MD5函数
				md.update(str.getBytes());
				byte b[] = md.digest();
				int i;
				StringBuffer sb = new StringBuffer("");
				for (int offset = 0; offset < b.length; offset++) {
					i = b[offset];
					if (i < 0){
						i += 256;
					}
					if (i < 16){
						sb.append("0");
					}
					sb.append(Integer.toHexString(i));
				}
				md5 = sb.toString();
				if(bit == 16) {
					//截取32位md5为16位
					String md16 = md5.substring(8, 24).toString();
					md5 = md16;
					if (isUpper){
						md5 = md5.toUpperCase();
					}
					return md5;
				}
			}
			//转换成大写
			if (isUpper){
				md5 = md5.toUpperCase();
			}
		} catch (Exception e) {
			log.info("MD5加密异常",e);
		}

		return md5;
	}

}

package com.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * aes加解密工具类
 * aes是对称的可逆加密
 */
public class SignUtil {

  /**
   * 加密<br>
   * @param data  明文
   * @param key 密钥
   * @return  String 密文
   * @throws Exception
   */
  public static String encrypt (String data, String key) throws Exception {
    byte[] bytesKey = Base64.decodeBase64(key);
    SecretKeySpec secretKeySpec = new SecretKeySpec(bytesKey, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] bytes = cipher.doFinal(data.getBytes("UTF8"));
    return URLEncoder.encode(Base64.encodeBase64String(bytes),"utf-8");
  }

  /**
   * 解密<br>
   * @param data  密文
   * @param key 密钥
   * @return  String 明文
   * @throws Exception
   */
  public static String decrypt (String data, String key) throws Exception {
    data= URLDecoder.decode(data,"utf-8");
    byte[] bytesKey = Base64.decodeBase64(key);
    SecretKeySpec secretKeySpec = new SecretKeySpec(bytesKey, "AES");
    byte[] encryptBytes = Base64.decodeBase64(data);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
    byte[] decryptBytes = cipher.doFinal(encryptBytes);
    return new String(decryptBytes,"UTF-8");
  }

  
  public static String MD5Encrypt(String str) throws Exception {
    MessageDigest md5=MessageDigest.getInstance("MD5");
    BASE64Encoder base64en = new BASE64Encoder();
    //加密后的字符串
    String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
    return URLEncoder.encode(newstr,"utf-8");
  }
  /**
   * md5加密
   * @param data 需要加密的字符串
   * @return 返回类型 String
   */
  public static String MD5(String data) throws Exception {
      char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
      byte[] strTemp = data.getBytes();
      MessageDigest mdTemp = MessageDigest.getInstance("MD5");
      mdTemp.update(strTemp);
      byte[] md = mdTemp.digest();
      int j = md.length;
      char str[] = new char[j * 2];
      int k = 0;
      for (int i = 0; i < j; i++) {
          byte byte0 = md[i];
          str[k++] = hexDigits[byte0 >>> 4 & 0xf];
          str[k++] = hexDigits[byte0 & 0xf];
      }
      return new String(str);
  }
}

package com.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.IllegalCharsetNameException;
import java.security.SecureRandom;

public class OPSCipherUtil {

    /**
     * 秘钥
     */
    public static final String KEY = "xxxffftttt";
    /**
     * 偏移量
     */
    public static final String IV = "456789ioyu";
    private static final String AES = "AES";
    private static final String AES_CBC = "xxx";
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String DEFAULT_CHARACTER = "UTF-8";

    /**
     * 加密
     *
     * @param input 需要加密的文本
     * @param key   密钥
     * @param iv    偏移量
     * @return 加密后字符串
     */
    public static String encrypt(String input, String key, String iv) {
        try {
            byte[] result = execAES(input.getBytes(DEFAULT_CHARACTER), hexDecode(key), hexDecode(iv), Cipher.ENCRYPT_MODE);
            return hexEncode(result);
        } catch (Exception e) {
            throw new IllegalCharsetNameException(DEFAULT_CHARACTER);
        }
    }

    /**
     * 解密
     *
     * @param input 需要解密的文本
     * @param key   密钥
     * @param iv    偏移量
     * @return 解密后字符串
     */
    public static String decrypt(String input, String key, String iv) {
        byte[] result = execAES(hexDecode(input), hexDecode(key), hexDecode(iv), Cipher.DECRYPT_MODE);
        return new String(result);
    }

    /**
     * 执行AES加解密操作
     *
     * @param input 加密或解密的原始文
     * @param key   密钥
     * @param iv    偏移量
     * @param mode  加密或解密C
     */
    public static byte[] execAES(byte[] input, byte[] key, byte[] iv, int mode) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, AES);
            Cipher cipher = Cipher.getInstance(AES_CBC);
            cipher.init(mode, secretKey, new IvParameterSpec(iv));
            return cipher.doFinal(input);
        } catch (Exception e) {
            String modeStr = "";
            switch (mode) {
                case Cipher.ENCRYPT_MODE:
                    modeStr = "Encrypt";
                    break;
                case Cipher.DECRYPT_MODE:
                    modeStr = "Decrypt";
            }
            throw new IllegalStateException(modeStr + " contant exception", e);
        }
    }

    /**
     * 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
     */
    public static byte[] generateIV() {
        byte[] bytes = new byte[16];
        new SecureRandom().nextBytes(bytes);
        return bytes;
    }

    /**
     * Hex编码.
     */
    public static String hexEncode(byte[] data) {
        // return DatatypeConverter.printHexBinary(data);
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }

    /**
     * Hex解码.
     */
    public static byte[] hexDecode(String input) {
        // return DatatypeConverter.parseHexBinary(input);
        char[] data = input.toLowerCase().toCharArray();
        int len = data.length;

        if (len % 2 != 0) {
            throw new IllegalStateException("Odd number of characters.");
        }

        byte[] out = new byte[len / 2];

        // two characters form the hex value.
        for (int i = 0; i < out.length; i++) {
            out[i] = (byte) (toDigit(data[i * 2], i * 2) << 4 | toDigit(data[i * 2 + 1], i * 2 + 1));
        }
        return out;
    }

    private static int toDigit(char ch, int index) {
        if (ch >= '0' && ch <= '9') {
            return ch - '0';
        } else if (ch >= 'a' && ch <= 'f') {
            return (ch - 'a') + 10;
        } else if (ch >= 'A' && ch <= 'F') {
            return (ch - 'A') + 10;
        } else {
            throw new IllegalStateException("Illegal numeric value of the charcter " + ch + " at index " + index);
        }
    }
}

12.时间工具类

package com.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class DateUtil {

	/**
	 * 日期格式化
	 */
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
	public static SimpleDateFormat sdf_yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
	public static  SimpleDateFormat sdfNormal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat sdf_yyyymmddhh24miss = new SimpleDateFormat("yyyyMMddHHmmss");
	private static final String DEFAULT_PATTERN = "yyyy-MM-dd";

	private static final String MONTH_PATTERN = "MM.dd";

	private static final String DEFAULT_DELIM = "-";
	/**
	 * yyyy-MM-dd HH:mm:ss
	 */
	public static String yyyyMMddHHmmssSpt = "yyyy-MM-dd HH:mm:ss";
	public static String yyyyMMddHHmmssSSpt = "yyyy-MM-dd HH:mm:ss.S";
	/**
	 * yyyy-MM-dd HH:mm
	 */
	public static String yyyyMMddHHmmSpt = "yyyy-MM-dd HH:mm";
	public static String yyyyMMddSpt = "yyyy-MM-dd";
	/**
	 * yyyyMMdd
	 */
	public static String yyyyMMdd = "yyyyMMdd";
	public static String yyyyMMSpt = "yyyy-MM";
	public static String HHmmssSpt = "HH:mm:ss";
	public static String HHmmSpt = "HH:mm";

	/**
	 * 转换日期 string to date
	 * @param dataTime
	 * @param pattern
	 * @return
	 */
	public static Date parseDateTime(String dataTime,String pattern){
		try {
			return new SimpleDateFormat(pattern).parse(dataTime);
		} catch (ParseException e) {
			e.printStackTrace();
			return new Date(dataTime);
		}
	}
	/**
	 * date to string
	 * Description:<br>
	 * 
	 * @param dataTime
	 * @param pattern
	 * @return
	 */
	public static String parseDateTime(Date dataTime,String pattern) {
		return new SimpleDateFormat(pattern).format(dataTime);
	}
	/**
	 * string to string 
	 * Description:<br>
	 * 
	 * @param dataTime
	 * @param pattern
	 * @return
	 */
	public static String parseDateTimeString2String(String dataTime,String pattern) {
		return parseDateTime(parseDateTime(dataTime, pattern), pattern);
	}
	/**
	 * date to date
	 * Description:<br>
	 * 
	 * @return
	 */
	public static Date parseDate2Date(Date d,String pattern){
		String formatString=parseDateTime(d, pattern);
		return parseDateTime(formatString, pattern);
	}
	
	/**
	 * 验证日期是否合法(yyyy-MM-dd)
	 * @param sDate
	 * @return
	 */
	public static boolean isValidDate(String sDate) {
	    String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
		//String datePattern1 = fmt;
	     String datePattern2 = "^((\\d{2}(([02468][048])|([13579][26]))"
	             + "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
	             + "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
	             + "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("
	             + "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"
	             + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
	     if ((sDate != null)) {
	         Pattern pattern = Pattern.compile(datePattern1);
	         Matcher match = pattern.matcher(sDate);
	         if (match.matches()) {
	             pattern = Pattern.compile(datePattern2);
	             match = pattern.matcher(sDate);
	             return match.matches();
	         }
	         else {
	             return false;
	         }
	     }
	     return false;
	 }


	/**
	 * Get the first day of month
	 * 
	 * @param pattern
	 *            e.g. MM.dd yyyy-MM-dd
	 * @return
	 */
	public static String getFirstDayOfMonth(String pattern) {
		if (pattern == null){
			pattern = MONTH_PATTERN;
		}
		Calendar date = Calendar.getInstance();
		date.set(Calendar.DATE, 1);// set the first day of month
		return new SimpleDateFormat(pattern).format(date.getTime());
	}

	/**
	 * Get the current day of month
	 * 
	 * @param pattern
	 *            e.g. MM.dd yyyy-MM-dd
	 * @return
	 */
	public static String getCurrentDayOfMonth(String pattern) {
		if (pattern == null){
			pattern = MONTH_PATTERN;
		}
		Calendar date = Calendar.getInstance();
		return new SimpleDateFormat(pattern).format(date.getTime());
	}

	/**
	 * Get the begin date and end date for query request
	 * 
	 * @param pattern
	 * @param delim
	 * @return
	 */
	public static String getBeginEndDate(String pattern, String delim) {
		if (delim == null){
			delim = DEFAULT_DELIM;
		}
		return getFirstDayOfMonth(pattern) + delim + getCurrentDayOfMonth(pattern);
	}

	/**
	 * Get the begin date and end date for query request
	 * @return
	 */
	public static String getDefaultBeginEndDate() {
		return getFirstDayOfMonth(MONTH_PATTERN) + DEFAULT_DELIM + getCurrentDayOfMonth(MONTH_PATTERN);
	}

	/**
	 * Get the begin date and end date for query request
	 * @return
	 */
	public static String getBeforeDayBeginEndDate() {
		return getFirstDayOfMonth(MONTH_PATTERN) + DEFAULT_DELIM + getBeforeDayOfMonth(MONTH_PATTERN);
	}

	private static String getBeforeDayOfMonth(String pattern) {
		if (pattern == null){
			pattern = MONTH_PATTERN;
		}
		Calendar date = Calendar.getInstance();
		date.add(Calendar.DATE, -1);
		return new SimpleDateFormat(pattern).format(date.getTime());
	}

	/**
	 * 
	 * @return
	 */
	public static String getDefaultQueryDate() {
		Calendar date = Calendar.getInstance();
		return new SimpleDateFormat(DEFAULT_PATTERN).format(date.getTime());
	}

	/**
	 * 获取上个月第一天的日期
	 * 
	 * @return
	 */
	public static String getFirstDayOfLastMonth(String pattern) {
		if (pattern == null){
			pattern = DEFAULT_PATTERN;
		}
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DATE, 1);
		cal.add(Calendar.MONTH, -1);
		return new SimpleDateFormat(pattern).format(cal.getTime());
	}

	/**
	 * 获取上个月最后一天的日期
	 * 
	 * @return
	 */
	public static String getLastDayOfLastMonth(String pattern) {
		if (pattern == null){
			pattern = DEFAULT_PATTERN;
		}
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1);
		int MaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), MaxDay);
		return new SimpleDateFormat(pattern).format(cal.getTime());
	}

	public static String getBeginEndDateOfLastMonth(String delim) {
		if (delim == null){
			delim = DEFAULT_DELIM;
		}
		return getFirstDayOfLastMonth(MONTH_PATTERN) + delim + getLastDayOfLastMonth(MONTH_PATTERN);
	}

	/**
	 * 获取套餐余量的开始与结束时间 时间格式:2012-08-17至2012-08-17
	 * 
	 * @return
	 */
	public static String getPackageFlowDayMonth() {
		Calendar cal = Calendar.getInstance();

		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DATE);

		String result = "";
		switch (month) {
		case 0:
			if (day == 1) {
				year = year - 1;
				cal.set(year, 11, 1);
				result += (year) + "-12-1至" + (year) + "-12-" + cal.getActualMaximum(Calendar.DATE);
			} else {
				result += year + "-" + (month + 1) + "-1至" + year + "-" + (month + 1) + "-" + (day - 1);
			}
			break;
		default:
			if (day == 1) {
				cal.set(year, month - 1, 1);
				result += year + "-" + month + "-1" + "至" + year + "-" + month + "-" + cal.getActualMaximum(Calendar.DATE);
			} else {
				result += year + "-" + (month + 1) + "-1" + "至" + year + "-" + (month + 1) + "-" + (day - 1);
			}
			break;
		}

		return result;
	}

	/**
	 * 获取指定时间属于星期几
	 * @param date 指定时间
	 * @return 1、2、3、4、5、6、0。0:周末
	 */
	public static int getDayOfTheWeek(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		int dayOfTheWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		return dayOfTheWeek;
	}

	/**
	 * 获取当天零点的时间
	 * @return
	 */
	public static Date getSameDayZeroPoint() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

    /**
     * 获取当天末尾的时间
     * @return
     */
	public static Date getSameDayEnd() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return calendar.getTime();
	}

	/**
	 * 获取下个周五的日期
	 * @return
	 */
	public static LocalDate getNextFriday() {
		return LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.of(5)));
	}

	/**
	 * 获取两个时间之间相差的秒数
	 * @param beginDate 开始时间
	 * @param endDate 结束时间
	 * @return 相差的秒数
	 */
	public static int getSecondDifference(Date beginDate, Date endDate) {
		return Integer.parseInt(((endDate.getTime() - beginDate.getTime()) / 1000) + "");
	}

	/**
	 * 现在到次日凌晨所剩秒数
	 * @return 秒
	 */
	public static int secondDistanceDay() {
		Calendar c = Calendar.getInstance();
		long now = c.getTimeInMillis();
		c.add(Calendar.DAY_OF_MONTH, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		return parseSecond(c, now);
	}

	private static int parseSecond(Calendar calendar, long now) {
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		Long millisecond = calendar.getTimeInMillis() - now;
		millisecond = millisecond / 1000;
		return millisecond.intValue();
	}

	/**
	 * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
	 *
	 * @param nowTime 当前时间
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @return true:在该区间
	 * @author jqlin
	 */
	private static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
		if (nowTime.getTime() == startTime.getTime()
				|| nowTime.getTime() == endTime.getTime()) {
			return true;
		}
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);
		Calendar begin = Calendar.getInstance();
		begin.setTime(startTime);
		Calendar end = Calendar.getInstance();
		end.setTime(endTime);
		return (date.after(begin) && date.before(end));
	}
}

package com.utils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import org.apache.log4j.Logger;

import com.util.StringUtils;

/**
 * 日期工具类,提供时间转换、比较、格式化等各种常用方法
 * 新增getDate方法,修改getNowDate方法以及其它几个使用了toLocaleString()的方法,解决Linux下时间错误问题
 */

public class DateStringUtil {
	private static Logger LOG = Logger.getLogger(DateStringUtil.class); // 日志记录
	/**
	 * 时间间隔:日
	 */
	public final static int DATE_INTERVAL_DAY = 1;
	/**
	 * 时间间隔:周
	 */
	public final static int DATE_INTERVAL_WEEK = 2;
	/**
	 * 时间间隔:月
	 */
	public final static int DATE_INTERVAL_MONTH = 3;
	/**
	 * 时间间隔:年
	 */
	public final static int DATE_INTERVAL_YEAR = 4;
	/**
	 * 时间间隔:小时
	 */
	public final static int DATE_INTERVAL_HOUR = 5;
	/**
	 * 时间间隔:分钟
	 */
	public final static int DATE_INTERVAL_MINUTE = 6;
	/**
	 * 时间间隔:秒
	 */
	public final static int DATE_INTERVAL_SECOND = 7;
	/**
	 * 时间格式:年月日
	 */
	public final static String DATE_FORMAT_YMD = "yyyy-MM-dd";
	/**
	 * 时间格式:带中文年月日
	 */
	public final static String DATE_FORMAT_YMD_C = "yyyy年MM月dd日";
	/**
	 * 时间格式:年月日
	 */
	public final static String DATE_FORMAT_YMDD = "yyyyMMdd";

	/**
	 * 时间格式:年月
	 */
	public final static String DATE_FORMAT_YM = "yyyyMM";
	/**
	 * 时间格式:年月日时分秒
	 */
	public final static String DATE_FORMAT_YMDHMS = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 时间格式:年月日时分秒
	 */
	public final static String DATE_FORMAT_YMD_HMS = "yyyyMMddHHmmss";

	/**
	 * 时间格式:年月
	 */
	public final static String DATE_FORMAT_YMC = "yyyy年MM月";
	/**
	 * 获取当月的最后一天,精确到 yyyyMMdd 23:59:59
	 * @author panbenle
	 * @creationDate. 2017年11月23日 下午2:49:33 
	 * @param date
	 * @return
	 */
	public static Date getMonthLastDay (Date date){
		Date mothLast = null;
		mothLast = getLast(date);
		Calendar para = Calendar.getInstance();
		para.setTime(mothLast);
		para.set(Calendar.HOUR_OF_DAY, 23);
		para.set(Calendar.MINUTE, 59);
		para.set(Calendar.SECOND, 59);
		para.set(Calendar.MILLISECOND,999);
		return para.getTime();
	}
	
	
	/**
	 * 获得时间
	 * @param date
	 *            时间
	 * @param dateFormat
	 *            时间格式
	 * @return 时间
	 */
	public static Date getDate(Date date, String dateFormat) {
		return dateFormat(dateFormat(date, dateFormat), dateFormat);
	}

	/**
	 * 获得当前日期(年月日)
	 * @return 当前时间(yyyy-MM-dd)
	 */
	public static Date getNowDate() {
		return dateFormat(dateFormat(new Date(), DATE_FORMAT_YMD),
				DATE_FORMAT_YMD);
	}

	/**
	 * 获取当前时间字符串(年月日)
	 * @return 时间字符串
	 */
	public static String getNowStringDate() {
		return dateFormat(new Date(), DATE_FORMAT_YMD);
	}

	/**
	 * 获得当前时间(年月日时分秒)
	 * @return 当前时间(yyyy-MM-dd HH:mm:ss)
	 */
	public static Date getNowTime() {
		return dateFormat(dateFormat(new Date(), DATE_FORMAT_YMDHMS),
				DATE_FORMAT_YMDHMS);
	}

	/**
	 * 获取当前时间字符串(年月日时分秒)
	 * @return 时间字符串
	 */
	public static String getNowStringTime() {
		return dateFormat(new Date(), DATE_FORMAT_YMDHMS);
	}

	/**
	 * 获得明天的日期字符串(格式年月日)
	 * @return 明天的日期
	 */
	public static String getTomorrowStringDate() {
		return dateFormat(getTomorrowTime(), DATE_FORMAT_YMD);
	}

	/**
	 * 获得明天的日期(年月日)
	 * @return 明天的日期
	 */
	public static Date getTomorrowDate() {
		return dateAdd(DATE_INTERVAL_DAY, getNowDate(), 1);
	}

	/**
	 * 获得明天的时间(年月日时分秒)
	 * @return 明天的时间
	 */
	public static Date getTomorrowTime() {
		return dateAdd(DATE_INTERVAL_DAY, getNowTime(), 1);
	}

	/**
	 * 获得昨天的日期
	 * @return 昨天的日期
	 */
	public static Date getYesterdayDate() {
		return dateAdd(DATE_INTERVAL_DAY, getNowDate(), -1);
	}

	/**
	 * 获得月初
	 * @param date
	 *            时间
	 * @return 月初日期
	 */
	public static Date getFirst(Date date) {
		Calendar firstDate = Calendar.getInstance();
		firstDate.setTime(date);
		firstDate.set(Calendar.DATE, 1); // 设为月初
		return getDate(firstDate.getTime(), DATE_FORMAT_YMD);
	}

	/**
	 * 获得月末
	 * @param date
	 *            时间
	 * @return 月末日期
	 */
	public static Date getLast(Date date) {
		date = dateAdd(DATE_INTERVAL_MONTH, date, 1); // 获得该日期下月的今天
		Date nextMonthFirst = getFirst(date); // 获得该日期下月初
		return getYesterMonthLast(nextMonthFirst); // 下月初-1得到上月末
	}

	/**
	 * 获取当月第一天
	 * @return 日期
	 */
	public static Date getMonthFirst() {
		Calendar firstDate = Calendar.getInstance();
		firstDate.set(Calendar.DATE, 1); // 设为月初
		return getDate(firstDate.getTime(), DATE_FORMAT_YMD);
	}

	/**
	 * 获取上月最后一天
	 * @return 日期
	 */
	public static Date getYesterMonthLast() {
		return getYesterMonthLast(getMonthFirst());
	}

	/**
	 * 获取指定月上月最后一天
	 * @return 日期
	 */
	public static Date getYesterMonthLast(Date date) {
		return dateAdd(DATE_INTERVAL_DAY, date, -1);
	}

	/**
	 * 获得下个月第一天的日期
	 * @return 日期
	 */
	public static Date getNextMonthFirst() {
		Calendar lastDate = Calendar.getInstance();
		lastDate.add(Calendar.MONTH, 1); // 加一个月
		lastDate.set(Calendar.DATE, 1); // 把日期设置为当月第一天
		return getDate(lastDate.getTime(), DATE_FORMAT_YMD);
	}

	/**
	 * 取得当前星期几
	 * @param date
	 *            时间
	 * @return 星期
	 */
	public static String getWeekOfDate(Date date) {
		if (date == null)
			return null;
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return weekDays[w];
	}

	/**
	 * 获取本周日日期
	 */
	public static String getWeekLast() {
		Calendar cal = Calendar.getInstance();
		// 这种输出的是上个星期周日的日期,因为老外那边把周日当成第一天
		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		// 增加一个星期,才是我们中国人理解的本周日的日期
		cal.add(Calendar.WEEK_OF_YEAR, 1);
		return dateFormat(cal.getTime(), DATE_FORMAT_YMD);
	}
	
	/**
	 * 获取本周一日期
	 */
	public static String getWeekFirst() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		return dateFormat(cal.getTime(), DATE_FORMAT_YMD);
	}

	/**
	 * 时间类型转换返回字符串
	 * @param date
	 *            时间
	 * @param dateFormat
	 *            时间格式
	 * @return 转换后的时间字符串
	 */
	public static String dateFormat(Date date, String dateFormat) {
		if (date == null)
			return null;
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		return format.format(date);
	}

	/**
	 * 字符串时间类型转换返回Date类型
	 * @param date
	 *            字符串时间
	 * @param dateFormat
	 *            时间格式
	 * @return 转换后的时间
	 */
	public static Date dateFormat(String date, String dateFormat) {
		if (StringUtils.isEmpty(date))
			return null;
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		try {
			return format.parse(date);
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return null;
		}
	}

	/**
	 * 加时间
	 * 
	 * @author sunju
	 * @creationDate. 2010-8-27 下午05:28:06
	 * @param interval
	 *            增加项,可以是天数、月份、年数、时间、分钟、秒
	 * @param date
	 *            时间
	 * @param num
	 *            加的数目
	 * @return 时间加后的时间
	 */
	public static Date dateAdd(int interval, Date date, int num) {
		if (date == null)
			return null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		switch (interval) {
		case DATE_INTERVAL_DAY:
			calendar.add(Calendar.DATE, num);
			break;
		case DATE_INTERVAL_WEEK:
			calendar.add(Calendar.WEEK_OF_MONTH, num);
			break;
		case DATE_INTERVAL_MONTH:
			calendar.add(Calendar.MONTH, num);
			break;
		case DATE_INTERVAL_YEAR:
			calendar.add(Calendar.YEAR, num);
			break;
		case DATE_INTERVAL_HOUR:
			calendar.add(Calendar.HOUR, num);
			break;
		case DATE_INTERVAL_MINUTE:
			calendar.add(Calendar.MINUTE, num);
			break;
		case DATE_INTERVAL_SECOND:
			calendar.add(Calendar.SECOND, num);
			break;
		default:
		}
		return calendar.getTime();
	}

	/**
	 * 两个时间时间差[前面时间和比较时间比,小于比较时间返回负数]
	 * 
	 * @author sunju
	 * @creationDate. 2010-8-27 下午05:26:13
	 * @param interval
	 *            比较项,可以是天数、月份、年数、时间、分钟、秒
	 * @param date
	 *            时间
	 * @param compare
	 *            比较的时间
	 * @return 时间差(保留两位小数点,小数点以后两位四舍五入)
	 */
	public static double getDateDiff(int interval, Date date, Date compare) {
		if (date == null || compare == null)
			return 0;
		double result = 0;
		double time = 0;
		Calendar calendar = null;
		switch (interval) {
		case DATE_INTERVAL_DAY:
			time = date.getTime() - compare.getTime();
			result = time / 1000d / 60d / 60d / 24d;
			break;
		case DATE_INTERVAL_HOUR:
			time = date.getTime() - compare.getTime();
			result = time / 1000d / 60d / 60d;
			break;
		case DATE_INTERVAL_MINUTE:
			time = date.getTime() / 1000d / 60d;
			result = time - compare.getTime() / 1000d / 60d;
			break;
		case DATE_INTERVAL_MONTH:
			calendar = Calendar.getInstance();
			calendar.setTime(date);
			time = calendar.get(Calendar.YEAR) * 12d;
			calendar.setTime(compare);
			time -= calendar.get(Calendar.YEAR) * 12d;
			calendar.setTime(date);
			time += calendar.get(Calendar.MONTH);
			calendar.setTime(compare);
			result = time - calendar.get(Calendar.MONTH);
			break;
		case DATE_INTERVAL_SECOND:
			time = date.getTime() - compare.getTime();
			result = time / 1000d;
			break;
		case DATE_INTERVAL_WEEK:
			calendar = Calendar.getInstance();
			calendar.setTime(date);
			time = calendar.get(Calendar.YEAR) * 52d;
			calendar.setTime(compare);
			time -= calendar.get(Calendar.YEAR) * 52d;
			calendar.setTime(date);
			time += calendar.get(Calendar.WEEK_OF_YEAR);
			calendar.setTime(compare);
			result = time - calendar.get(Calendar.WEEK_OF_YEAR);
			break;
		case DATE_INTERVAL_YEAR:
			calendar = Calendar.getInstance();
			calendar.setTime(date);
			time = calendar.get(Calendar.YEAR);
			calendar.setTime(compare);
			result = time - (double) calendar.get(Calendar.YEAR);
			break;
		default:
			break;
		}
		return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP)
				.doubleValue();
	}

	/**
	 * 获取时间差[前面时间和比较时间比,小于比较时间返回负数]
	 * 
	 * @author sunju
	 * @creationDate. 2010-9-1 下午04:36:07
	 * @param level
	 *            返回时间等级(1:返回天;2:返回天-小时;3:返回天-小时-分4:返回天-小时-分-秒;)
	 * @param date
	 *            时间
	 * @param compare
	 *            比较的时间
	 * @return 时间差(保留两位小数点,小数点以后两位四舍五入)
	 */
	public static String getDateBetween(Integer level, Date date, Date compare) {
		if (date == null || compare == null)
			return null;
		long s = new BigDecimal(
				getDateDiff(DATE_INTERVAL_SECOND, date, compare)).setScale(2,
				BigDecimal.ROUND_HALF_UP).longValue();
		int ss = 1;
		int mi = ss * 60;
		int hh = mi * 60;
		int dd = hh * 24;

		long day = s / dd;
		long hour = (s - day * dd) / hh;
		long minute = (s - day * dd - hour * hh) / mi;
		long second = (s - day * dd - hour * hh - minute * mi) / ss;
		String flag = (day < 0 || hour < 0 || minute < 0 || second < 0) ? "-"
				: "";
		day = Math.abs(day);
		hour = Math.abs(hour);
		minute = Math.abs(minute);
		second = Math.abs(second);
		StringBuilder result = new StringBuilder(flag);
		switch (level) {
		case 1:
			if (day != 0)
				result.append(day).append("天");
			break;
		case 2:
			if (day != 0)
				result.append(day).append("天");
			if (hour != 0)
				result.append(hour).append("小时");
			break;
		case 3:
			if (day != 0)
				result.append(day).append("天");
			if (hour != 0)
				result.append(hour).append("小时");
			if (minute != 0)
				result.append(minute).append("分");
			break;
		case 4:
			if (day != 0)
				result.append(day).append("天");
			if (hour != 0)
				result.append(hour).append("小时");
			if (minute != 0)
				result.append(minute).append("分");
			if (second != 0)
				result.append(second).append("秒");
			break;
		default:
			break;
		}
		return result.toString();
	}

	/**
	 * 时间是否是今天
	 * 
	 *            时间
	 * @return 布尔
	 */
	public static boolean isToday(Date date) {
		if (date == null)
			return false;
		return getNowStringDate().equals(dateFormat(date, DATE_FORMAT_YMD));
	}

	/**
	 * 时间是否合法
	 * 
	 *            时间
	 * @param dateFormat
	 *            时间格式
	 * @return
	 */
	public static boolean isValidDate(String date, String dateFormat) {
		try {
			new SimpleDateFormat(dateFormat).parse(date);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/*
	 * 以下为兼容的旧方法
	 */
	public static Date getDateFromString(String dateStr, int last) {
		try {
			Date date = dateFormat(dateStr, DATE_FORMAT_YMD);
			return dateAdd(DATE_INTERVAL_DAY, date, last);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 字符串转换为日期
	 */
	public static Date strToDate(String str) {
		return dateFormat(str, "yyyyMMddHHmmss");
	}

	/*
	 * 取当前年月
	 */
	public static String getYearMonth() {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		return year + "" + (month < 10 ? "0" + month : month);
	}

	/**
	 * 时间比较
	 * @return date1 早于 date2 返回true
	 */
	public static boolean comperdate(Date date1, Date date2) {
		if (date1 != null && date2 != null) {
			if (date1.getTime() < date2.getTime()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 时间比较 判断date3是否在date1和date2之间
	 *            开始时间
	 * @param date2
	 *            结束时间
	 * @param date3
	 *            需要判断的时间
	 * @return
	 */
	public static boolean comperdate(Date date1, Date date2, Date date3) {
		if (date1 != null && date2 != null && date3 != null) {
			if (date3.getTime() > date1.getTime()) {
				if (date3.getTime() < date2.getTime()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 是否出账期 每月1、2号,3号8点前为出账期
	 * @author 涂小炼
	 * @creationDate. 2015-7-1 上午10:47:22
	 * @return
	 */
	public static boolean isAccountPeriod() {
		Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DAY_OF_MONTH);
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		return day < 3 || (day == 3 && hour < 8);
	}

	/**
	 * 获取两个时间的天数差
	 * 
	 * @param smdate
	 * @param bdate
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}
	
	/*
	 * 判断两个时间是否处在同一个月
	 */
	public static boolean isSameMonth(Date dateA, Date dateB){
		Calendar c=Calendar.getInstance();
		c.setTime(dateA);
		int month1=c.get(Calendar.MONTH);
		c.setTime(dateB);
		int month2=c.get(Calendar.MONTH);
		return month1==month2;
		
	}
	
	/**
	 * 时间格式转solr格式
	 * 
	 * @author xuli
	 * @creationDate. 2019-1-23 下午16:00:00
	 * @return
	 */
	public static String getSolrDate(Date date) {  
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");  
		SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");  
		sdf1.setTimeZone(TimeZone.getTimeZone("UTC")); 
		sdf2.setTimeZone(TimeZone.getTimeZone("UTC"));  
		String result = sdf1.format(date) + "T" + sdf2.format(date) + "Z";  
		return result; 
	}
	
	/**
	 * 获取traId,作为秒杀接口入参
	 * 
	 * @author xuli
	 * @creationDate. 2019-3-29 上午11:40:00
	 * @return
	 */
	public static String getTraId(){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
		String date=sdf.format(new Date());
		Random random = new Random();
	    String fourRandom = random.nextInt(10000) + "";
	    int randLength = fourRandom.length();
	    if(randLength<4){
	    	for(int i=1; i<=4-randLength; i++){
	    		fourRandom = "0" + fourRandom;
	    	}
	    }
	    return date+fourRandom;
	}
	
	/**
	 * 获取traId,作为秒杀接口入参
	 * 
	 * @author xuli
	 * @creationDate. 2019-4-17 上午11:40:00
	 * @return
	 */
	public static String getHttpTraId(){
		Random random = new Random();
	    String fourRandom = random.nextInt(10000) + "";
	    int randLength = fourRandom.length();
	    if(randLength<4){
	    	for(int i=1; i<=4-randLength; i++){
	    		fourRandom = "0" + fourRandom;
	    	}
	    }
	    return fourRandom;
	}
	
	public static String getMessageId(){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String date=sdf.format(new Date());
		Random random = new Random();
		String result="";
		for (int i=0;i<6;i++){
			result+=random.nextInt(10);
		}
		return date+result;
	}
	
	/**
	 * 得到时间范围
	 * @param date 日期
	 * @param unit 单位,1天,2月,3一次性,4周
	 * @return
	 * @author xuli
	 * @creationDate. 2019-9-10 上午11:40:00
	 */
	public static String[] getTimeRange(Date date,String unit){
	    String[] timeRange =DateStringUtil.getDayTimeRange(date);;
	    if ("1".equals(unit)) {// 按天
            timeRange=DateStringUtil.getDayTimeRange(date);
        } else if ("2".equals(unit)) {// 按月
            timeRange=DateStringUtil.getMonthTimeRange(date);
        } else if ("4".equals(unit)) {// 按周
            timeRange=DateStringUtil.getWeekTimeRange(date);
        }else if ("3".equals(unit)) {// 一次性有效
            timeRange=new String[]{null,null};
        }else{//一年
            Calendar d=Calendar.getInstance();
            d.setTime(date);
            d.add(Calendar.YEAR, 1);
            timeRange=new String[]{DateStringUtil.format(date, DATE_FORMAT_YMD),DateStringUtil.format(d.getTime(), DATE_FORMAT_YMD)};
        }
	    return timeRange;
	}
	
	/**
	 * 
	 * 
	 * @param date
	 * @return [today 00:00:00, tomorrow 00:00:00]
	 */
	public static String[] getDayTimeRange(Date date){
		Calendar cal = Calendar.getInstance();
		if (date != null) cal.setTime(date);
		String[] ret = new String[2];
		final String zeroTime = " 00:00:00";
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ret[0] = sdf.format(cal.getTime()) + zeroTime;
		cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1);
		ret[1] = sdf.format(cal.getTime()) + zeroTime;
		return ret;
	}
	
	public static String[] getMonthTimeRange(Date date){
		Calendar cal = Calendar.getInstance();
		if (date != null) cal.setTime(date);
		String[] ret = new String[2];
		final String zeroTime = " 00:00:00";
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		cal.set(Calendar.DAY_OF_MONTH, 1);
		ret[0] = sdf.format(cal.getTime()) + zeroTime;
		cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
		ret[1] = sdf.format(cal.getTime()) + zeroTime;
		return ret;
	}
	
	public static String[] getWeekTimeRange(Date date){
		Calendar cal = Calendar.getInstance();
		if (date != null) cal.setTime(date);
		cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
		int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天
		cal.add(Calendar.DATE, cal.getFirstDayOfWeek()-day);//根据日历的规则,给当前日期减去星期几与一个星期第一天的差值  		
		String[] ret = new String[2];
		final String zeroTime = " 00:00:00";
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ret[0] = sdf.format(cal.getTime()) + zeroTime;
		cal.add(Calendar.DAY_OF_WEEK, 7);
		ret[1] = sdf.format(cal.getTime()) + zeroTime;
		return ret;
	}
	
	public static String format(Date date, String format) {
		return new SimpleDateFormat(format).format(date);
	}

	public static void main(String[] args) {
		// System.out.println(getDateBetween(Integer.valueOf(4),
		// dateFormat("2011-05-4 20:02:05", "yyyy-MM-dd HH:mm:ss"), new
		// Date()));
		// System.out.println(getDateDiff(DATE_INTERVAL_DAY,
		// dateFormat("2010-11-16 10:20:38", DATE_FORMAT_YMDHMS),
		// dateFormat("2010-11-12 23:32:53", DATE_FORMAT_YMDHMS)));
		// System.out.println(getDateBetween(4,
		// dateFormat("2010-11-16 10:20:38", DATE_FORMAT_YMDHMS),
		// dateFormat("2010-11-12 23:32:53", DATE_FORMAT_YMDHMS)));
		// System.out.println(getWeekOfDate(dateFormat("2011-1-10 12:37:52",
		// DATE_FORMAT_YMDHMS)));
		// System.out.println(isValidDate("2012-05-08 12:00:00",
		// "yyyy-MM-dd HH:mm:ss"));
		// Date timestamp = dateFormat("2012-06-19 13:33:02",
		// "yyyy-MM-dd HH:mm:ss");;
		// double dateDiff = getDateDiff(DATE_INTERVAL_MINUTE, new Date(),
		// timestamp);
		// System.out.println("dateDiff-->" + dateDiff);
		// if (dateDiff > 6) {
		// System.out.println("超时");
		// }
		/*
		 * System.out.println(DateStringUtil.dateFormat(new Date(),
		 * "yyyy年MM月dd日HH时mm分")); // 取到明天的今天 Date nextYear =
		 * DateStringUtil.dateAdd(DateStringUtil.DATE_INTERVAL_YEAR, new Date(),
		 * 1); System.out.println(DateStringUtil.dateFormat(nextYear,
		 * DateStringUtil.DATE_FORMAT_YMDHMS));
		 * System.out.println(getNowStringTime());
		 * System.out.println(getYesterdayDate());
		 * System.out.println(getMonthFirst());
		 * System.out.println(getNextMonthFirst());
		 */
		// System.err.println(getNowStringDate());
		// System.err.println(getNowStringDate().substring(8,10));
		// System.out.println(getYearMonth());
		// System.out.println(getFirst(dateAdd(DATE_INTERVAL_MONTH,new
		// Date(),-5)));
		System.out.println(isAccountPeriod());
	}
}

13.ip获取工具类

public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

14.正则校验工具类

  1 import java.util.regex.Pattern;
  2 
  3 /**
  5  * @description: 校验工具类
  8  **/
  9 public class ValidatorUtil {
 10     /**
 11      * 正则表达式:验证用户名
 12      */
 13     public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,20}$";
 14 
 15     /**
 16      * 正则表达式:验证密码
 17      */
 18     public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,20}$";
 19 
 20     /**
 21      * 正则表达式:验证手机号
 22      */
 23     public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
 24 
 25     /**
 26      * 正则表达式:验证邮箱
 27      */
 28     public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
 29 
 30     /**
 31      * 正则表达式:验证汉字
 32      */
 33     public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$";
 34 
 35     /**
 36      * 正则表达式:验证身份证
 37      */
 38     public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
 39 
 40     /**
 41      * 正则表达式:验证URL
 42      */
 43     public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
 44 
 45     /**
 46      * 正则表达式:验证IP地址
 47      */
 48     public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
 49 
 50     /**
 51      * 校验用户名
 52      *
 53      * @param username
 54      * @return 校验通过返回true,否则返回false
 55      */
 56     public static boolean isUsername(String username) {
 57         return Pattern.matches(REGEX_USERNAME, username);
 58     }
 59 
 60     /**
 61      * 校验密码
 62      *
 63      * @param password
 64      * @return 校验通过返回true,否则返回false
 65      */
 66     public static boolean isPassword(String password) {
 67         return Pattern.matches(REGEX_PASSWORD, password);
 68     }
 69 
 70     /**
 71      * 校验手机号
 72      *
 73      * @param mobile
 74      * @return 校验通过返回true,否则返回false
 75      */
 76     public static boolean isMobile(String mobile) {
 77         return Pattern.matches(REGEX_MOBILE, mobile);
 78     }
 79 
 80     /**
 81      * 校验邮箱
 82      *
 83      * @param email
 84      * @return 校验通过返回true,否则返回false
 85      */
 86     public static boolean isEmail(String email) {
 87         return Pattern.matches(REGEX_EMAIL, email);
 88     }
 89 
 90     /**
 91      * 校验汉字
 92      *
 93      * @param chinese
 94      * @return 校验通过返回true,否则返回false
 95      */
 96     public static boolean isChinese(String chinese) {
 97         return Pattern.matches(REGEX_CHINESE, chinese);
 98     }
 99 
100     /**
101      * 校验身份证
102      *
103      * @param idCard
104      * @return 校验通过返回true,否则返回false
105      */
106     public static boolean isIDCard(String idCard) {
107         return Pattern.matches(REGEX_ID_CARD, idCard);
108     }
109 
110     /**
111      * 校验URL
112      *
113      * @param url
114      * @return 校验通过返回true,否则返回false
115      */
116     public static boolean isUrl(String url) {
117         return Pattern.matches(REGEX_URL, url);
118     }
119 
120     /**
121      * 校验IP地址
122      *
123      * @param ipAddr
124      * @return
125      */
126     public static boolean isIPAddr(String ipAddr) {
127         return Pattern.matches(REGEX_IP_ADDR, ipAddr);
128     }
129 }
                //姓名只能汉字加字母不超过30个字符
				if (invoiceName.length()>0 && invoiceName.length()<=30){
					Pattern compileName = Pattern.compile("^[\\u4e00-\\u9fa5A-Za-z]+$");
					if (compileName.matcher(invoiceName).matches()){
						//邮箱:只能正确后缀邮箱地址
						Pattern compileEmail = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
						if (!compileEmail.matcher(invoiceEmail).matches()){
							log.info("UUID:{}收票人邮箱地址不正确",uuid);
							return new APIResult("1","收票人邮箱地址不正确","");
						}else {
							log.info("UUID:{}收票人信息验证通过",uuid);
							pushResult = "Y";
						}
					}

15.数据库连接工具类

  • 第一款
package com.common.jdbc;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.sql.*;
 
/**
 * @ClassNames JdbcUtilImpl
 * @Description 此实现类仅支持mysql数据库
 * @Author qtao
 * @Date 2019/8/27 11:19
 * Version 1.0
 **/
public class JdbcUtilImpl implements JdbcUtil {
 
    private Logger logger = LoggerFactory.getLogger(this.getClass());
 
    private String mysqlDriverClass = "com.mysql.jdbc.Driver";
    private String url_1 = "jdbc:mysql://";
    private String url_2 = "?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
 
    // 数据库IP
    private String database_ip = "192.168.159.51";
    // 数据库端口
    private String database_port = "3306";
    // 数据库名称
    private String database_name = "ssm_demo";
    // 数据库名称
    private String username = "root";
    // 数据库密码
    private String password = "root";
 
    private Connection con;
    private PreparedStatement psm;
    private ResultSet rs;
 
    /**
     * 获取数据库连接
     *
     * @return
     */
    private Connection getConnection() {
        try {
            Class.forName(this.mysqlDriverClass);
            String url = url_1 + database_ip + ":" + database_port + "/" + database_name + url_2;
            this.con = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            logger.error("获取数据库连接驱动失败,ClassNotFoundException={}", e);
        } catch (SQLException e) {
            logger.error("连接数据库失败,SQLException={}", e);
        }
        return con;
    }
 
    /**
     * 对SQL进行预编译
     *
     * @param sql
     */
    private void getPreparedStatement(String sql) {
        try {
            psm = con.prepareStatement(sql);
        } catch (SQLException e) {
            logger.error("对SQL进行预编译失败,SQLException={}", e);
        }
    }
 
    /**
     * 关闭数据库连接
     */
    public void closeConnection() {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            logger.error("关闭ResultSet连接失败,Exception={}", e);
        }
 
        try {
            if (psm != null) {
                psm.close();
            }
        } catch (SQLException e) {
            logger.error("关闭PreparedStatement连接失败,Exception={}", e);
        }
 
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            logger.error("关闭Connection连接失败,Exception={}", e);
        }
    }
 
    /**
     * 查询方法
     *
     * @param sql
     * @param obj
     * @return
     */
    public ResultSet query(String sql) {
        getConnection();
        getPreparedStatement(sql);
        try {
            rs = psm.executeQuery();
        } catch (SQLException e) {
            logger.error("查询时出现失败,SQLException={}", e);
        }
        return rs;
    }
 
    public boolean update(String sql) {
        getConnection();
        getPreparedStatement(sql);
        int num = 0;
        try {
            num = psm.executeUpdate();
        } catch (SQLException e) {
            logger.error("新增/更新/删除时出现失败,SQLException={}", e);
        } finally {
            closeConnection();
        }
        if (num > 0) {
            return true;
        }
        return false;
    }
 
}

    public static void main (String[] args){
        JdbcUtil jdbcUtil = new JdbcUtilImpl();
        String sql = "select * from USER";
        ResultSet rs = jdbcUtil.query(sql);
        List<User> list = new ArrayList<>();
        try {
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getLong("ID"));
                user.setName(rs.getString("NAME"));
                user.setEmail(rs.getString("EMAIL"));
                user.setPassword(rs.getString("PASSWORD"));
                user.setRemark(rs.getString("REMARK"));
                list.add(user);
            }
        } catch (Exception e){
            logger.error("异常,Exception={}",e);
        } finally {
            jdbcUtil.closeConnection();
        }
        for (User user : list){
            System.out.println("编号:"+user.getId());
            System.out.println("昵称:"+user.getName());
            System.out.println("邮箱:"+user.getEmail());
            System.out.println("备注:\n\t"+user.getRemark());
        }
    }
  • 第二款
package untils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * JDBC工具类
 */
public class HgJdbcUtils {
    //加载驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获得连接
    public static Connection getConnection(){
        try {
            DriverManager.getConnection("jdbc:mysql://localhost:3306/qy97?characterEnconding=utf-8","root","root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    /** 增删改的通用方法
     * @param String sql  要执行的sql
     * @param Object[] obj    对象类型的数组  里面存放着 sql执行的占位符参数
     *              【name,age,id】
     *                【id】
     *               【name,age】
     *         Object... 可变参数
     * */
    public static boolean executeUpdate(String sql,Object... args){
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            //有参数
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            //执行sql语句
            int i = ps.executeUpdate();
            //返回  true
            return i>0;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            close(conn,ps,null);
        }
        return false;
    }
    /**
     *  查询的通用方法
     * @param sql;
     * @param args;
     * @return
     * */
    public static List<Map<String,Object>> queryForList(String sql,Object... args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            //有可能有参数
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            //执行sql语句
            rs = ps.executeQuery();
            //创建List集合
            List<Map<String, Object>> list = new ArrayList<>();
            //获取本次查询结果集有多少列
            int count = rs.getMetaData().getColumnCount();
            //while循环
            while(rs.next()){
                //创建Map集合   获取一个数据封装成一个Map集合
                Map<String, Object> map = new HashMap<>();
                //for循环  遍历所有的列
                for(int i=0;i<count;i++){
                    //获取本次查询结果集的列名
                    String name = rs.getMetaData().getColumnLabel(i + 1);
                    map.put(name,rs.getObject(name));
                }
                //把所有的map集合添加到List集合中
                list.add(map);
            }
            //返回值
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            close(conn,ps,rs);
        }
        return null;
    }
    
    /**
     *  查询的通用方法
     * @param sql;
     * @param args;
     * @return
     * */
    public static Map<String,Object> queryForMap(String sql,Object... args){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            //有可能有参数
            for(int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            //执行sql语句
            rs = ps.executeQuery();
            //创建map集合
            Map<String, Object> map = new HashMap<>();
            //获取本次查询结果集有多少列
            int count = rs.getMetaData().getColumnCount();
            if(count>1) {
            	throw new RuntimeException("the query result is greater than one column");
            }
            //while循环
            while(rs.next()){
                //获取本次查询结果集的列名
                String name = rs.getMetaData().getColumnLabel(1);
                map.put(name,rs.getObject(name));
            }
            //返回值
            return map;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            close(conn,ps,rs);
        }
        return null;
    }
    
    
    /**
	 * @Function commonQueryOne
	 * @Description 查找单条记录
	 * @param sql 执行的SQL语句
	 * @param cls 实体类对象
	 * @param objects SQL语句中的限制条件
	 */
	public static <E> E queryForBean(String sql, Class<E> cls, Object...args) {
	    Connection conn = getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
		E entity = null;
		try {
			ps = conn.prepareStatement(sql);
			if(args != null && args.length > 0) {
				for(int i = 0; i < args.length; i++) {
					ps.setObject(i+1, args[i]);
				}
			}
			//获取结果集
			rs = ps.executeQuery();  
			
			/**
			 * 以下通过数据库表中字段去查找实体类中的属性名
			 */
			//获取结果集中对象的数量、列名等
			ResultSetMetaData rsmd = rs.getMetaData();  
			//获取字段数
			int columnCount = rsmd.getColumnCount();  
			while(rs.next()) {
				//ͨ通过反射获取实体类对象
				entity = cls.newInstance();  
				for(int i = 0; i < columnCount; i++) {
					//获取字段名称
					String columnName = rsmd.getColumnName(i+1); 
					//获取该字段对应的值ֵ
					Object columnValue = rs.getObject(columnName);  
					//通过字段名获取属性,try{名称不匹配}catch{到配置文件查找对应属性名}
					Field field = null;
					try{
						field = cls.getDeclaredField(columnName); 
					}catch (Exception e){
						throw new RuntimeException("The column name does not match the field name");
					}
					//将私有属性非可访问设置为可访问
					field.setAccessible(true);  
					//给实体类中的属性赋值ֵ
					field.set(entity, columnValue);  
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			 close(conn,ps,rs);
		}
		return entity;
	}
	
	
	//selectAll
		/**
		 * @Function commonQueryList
		 * @Description 查找多条记录
		 * @param sql 执行的SQL语句
		 * @param cls 实体类对象
		 * @param objects SQL语句中的限制条件
		 */
		public static <E> List<E> queryForBeanList(String sql,  Class<E> cls, Object...objects) {
		    Connection conn = getConnection();
	        PreparedStatement ps = null;
	        ResultSet rs = null;
			E entity = null;
			List<E> list = new ArrayList<E>();
			try {
				ps = conn.prepareStatement(sql);
				if(objects != null && objects.length > 0) {
					for(int i = 0; i < objects.length; i++) {
						ps.setObject(i+1, objects[i]);
					}
				}
				rs = ps.executeQuery();  
				
				ResultSetMetaData rsmd = rs.getMetaData();
				int columnCount = rsmd.getColumnCount();
				while(rs.next()) {
					entity = cls.newInstance();
					for(int i = 0; i < columnCount; i++) {
						String columnName = rsmd.getColumnName(i+1);
						Object columnValue = rs.getObject(columnName);
						//通过字段名获取属性,try{名称不匹配}catch{到配置文件查找对应名称}
						Field field = null;
						try{
							field = cls.getDeclaredField(columnName); 
						}catch (Exception e){
							throw new RuntimeException("The column name does not match the field name");
						}
						field.setAccessible(true);
						field.set(entity, columnValue);
					}
					list.add(entity);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				 close(conn,ps,rs);
			}
			return list;
		}
	
    
    
    /**
     *  关闭资源的通用方法
     * */
    public static void close(Connection conn,Statement stat,ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
            }
            if(stat!=null){
                stat.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

16.Logging日志配置

  • application.yml中引入
    在这里插入图片描述
  • logback-spring-pro.xml中配置如下
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework.web" level="ERROR"/>
    <!--value是部署的所在项目下的日志路径-->
    <property name="LOG_HOME" value="/app/logs/xxxx-pro" />
    <!--name是该日志示例的名字-->
    <property name="activeStep" value="/app/logs/monitor/bizactivity/xxx-pro" />
    <!--第三方接口监控日志记录-->
    <property name="outsideAPI" value="/app/logs/monitor/bizactivity/xxx-pro" />

    <!-- 按照每天生成应用日志文件 -->
    <appender name="FILE" class="logback.core.rolling.RollingFileAppender">
        <File>${LOG_HOME}/${WLS_NODE}/info.log</File>
        <append>true</append>
        <rollingPolicy class="logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${LOG_HOME}/${WLS_NODE}/info.log-%d{yyyyMMdd}</FileNamePattern>
        </rollingPolicy>
        <layout class="logback.classic.PatternLayout">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
            <pattern> %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} %L -%msg%n</pattern>
        </layout>
    </appender>

    <!--每日error日志-->
    <appender name="appErrorLog" class="logback.core.rolling.RollingFileAppender">
        <File>${LOG_HOME}/${WLS_NODE}/error.log</File>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <rollingPolicy class="logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/${WLS_NODE}/error-%d{yyyyMMdd}.log</fileNamePattern>
        </rollingPolicy>
        <layout class="logback.classic.PatternLayout">
            <pattern> %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} %L -%msg%n</pattern>
        </layout>
    </appender>

    <root level="INFO">
        <appender-ref ref="FILE" />
        <appender-ref ref="appErrorLog" />
    </root>

    <logger name="org.apache.kafka" level="ERROR"/>

    <!--活动步骤监控日志记录-->
    <appender name="activeStep" class="logback.core.rolling.RollingFileAppender">
        <File>${activeStep}/bizactivity.log</File>
        <append>true</append>
        <rollingPolicy class="logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${activeStep}/bizactivity+${WLS_NODE}+${ServiceIP}+%d{yyyyMMddHHmm}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%m%n</pattern>
        </encoder>
        <filter class="logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
    </appender>
    <logger name="activeStep" additivity="false" level="INFO">
        <appender-ref ref="activeStep"/>
    </logger>

    <!--第三方接口监控日志记录-->
    <appender name="outsideAPI" class="logback.core.rolling.RollingFileAppender">
        <File>${outsideAPI}/operaplatform.log</File>
        <append>true</append>
        <rollingPolicy class="logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${outsideAPI}/operaplatform+${WLS_NODE}+${ServiceIP}+%d{yyyyMMddHHmm}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%m%n</pattern>
        </encoder>
        <filter class="logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
    </appender>
    <logger name="outsideAPI" additivity="false" level="INFO">
        <appender-ref ref="outsideAPI"/>
    </logger>

    <logger name="redis.clients.jedis.Connection" level="ERROR"/>
</configuration>
  • java类
private Logger ActiveStepMonitorLog = LoggerFactory.getLogger("activeStep");

	@ResponseBody
	@RequestMapping("/xxx/v1")
	public APIResult getLogs(HttpServletRequest request){
		log.info("/some/nice/xxx/v1进入页面落日志");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		UserInfo userVo = getUserInfoFromRedis(request);
		try {
			//默认未登录
			String isOnline = "0";
			long start = System.currentTimeMillis();
			SimpleUserInfo simpleUserInfo = null;
			String step = "买买买";
			if (userVo != null) {
				if (StringUtils.equals(_NET, userVo.getNetType())){
					isOnline = "1";
				}
			}
			StepMonitorInfo stepMonitorInfo = StepMonitorInfo.getStepMonitor(
					request,simpleUserInfo, step, null, (System.currentTimeMillis() - start)+"", "2",
					null,null,null,"1",
					isUnicom, null, null, null, null, null, null, null, null, null, "");
			ActiveStepMonitorLog.info(stepMonitorInfo.toLogString());
			return new APIResult("0", "落日志成功", resultMap);
		} catch (Exception e) {
			log.error("/some/nice/xxx/v1进入页面落日志异常:",e);
			return new APIResult("1", "落日志异常", resultMap);
		}
	}

17.定时器任务

@EnableScheduling是spring自带的定时任务功能,很多人使用的是 quartz,而 SpringBoot自带的两个注解就可以轻松搞定
第一款:

package com.job;

import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.MakeUpInvoiceService;
import com.OrdercenterService;
import com.utils.APIResult;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisCluster;

@Slf4j
@Component
@Configuration
@EnableScheduling
public class DrawBilJob {
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	MakeUpInvoiceService makeUpInvoiceService;
	@Autowired
	private OrdercenterService ordercenterService;

	/**
	 * 定时处理开票信息 10分钟执行一次
	 */
	@Scheduled(cron = "0 0/10 * * * ?")
	public void tash() {
		String setnx = jedisCluster.set("DRAW_BIL_JOB", "running", "NX", "EX", 60);
		if (StringUtils.equals("OK", setnx)) {
			for (int i = 0; i < 100; i++) {
				String str = jedisCluster.lpop("MAKE_UP_INVOICE");
				try {
					if (StringUtils.isNoneBlank(str)) {
						JSONObject jsonObject = JSONObject.parseObject(str);
						log.info("定时处理开票信息队列取出开票信息:" + jsonObject);
						Map<String, Object> map = (Map<String, Object>) jsonObject;
						String uuid = (String) map.get("uuid");
						String orderNo = (String) map.get("orderNo");
						String userMobile = (String) map.get("userMobile");
						String invoiceTin = (String) map.get("invoiceTin");
						String invoiceType = (String) map.get("invoiceType");
						String invoiceName = (String) map.get("invoiceName");
						String invoicePhone = (String) map.get("invoicePhone");
						String invoiceEmail = (String) map.get("invoiceEmail");
						String invoiceTitle = (String) map.get("invoiceTitle");
						// 调用开票流程
						APIResult checkingticket = makeUpInvoiceService.checkingticket(userMobile, invoiceTitle,
								invoiceTin, invoiceType, invoicePhone, invoiceEmail, invoiceName, orderNo);
						log.info("UUID:{}换票流程开票结果为:{}", uuid, JSON.toJSONString(checkingticket));
						if (StringUtils.equals("1", checkingticket.getCode())) {
							// 更新发票状态为已换票
							map.put("invoiceReqNum", checkingticket.getResdata().toString());
							map.put("pushResult", "H");
							ordercenterService.saveticket(uuid, JSON.toJSONString(map));
						} else {
							jedisCluster.rpush("MAKE_UP_INVOICE", str);
						}
					}
				} catch (Exception e) {
					jedisCluster.rpush("MAKE_UP_INVOICE", str);
					log.error("定时处理开票信息队列异常原因为:", e);
				}
			}
		}
	}
}

其中Scheduled注解中有以下几个参数:

1.cron是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次 秒 分 时 天 月

2.zone表示执行时间的时区

3.fixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行

4.fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行

5.initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间
第二款

//1. maven依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
          
//2. 添加@EnableScheduling注解到入口类声明上面
package com.cun;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling   //开启定时任务注解
@SpringBootApplication
public class AsMailTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsMailTaskApplication.class, args);
    }
}

//3. 在具体实现方法的类上加@Component注解,在实现方法上加@Scheduled(fixedRate = 1000 * 30)注解,在方法中写要定时执行的任务
package com.cun.service;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TaskService {
    /**
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     * 例子:
     *  【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
     *  【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
     *  【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
     *  【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
     *  【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
     */
    @Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    public void runTask(){
        System.out.println(new Date()+"发布王者战报");
    }
}

注意:违返不生效
(1)此方法不能有参数

(2)此方法不能有返回值

(3)此类中不能包含其他带任何注解的方法

18.地市名称与编号对应map

package com.utils;
import java.util.HashMap;
import java.util.Map;

public class CityContrastRelation {

    public static final Map<String, String> cityMap = new HashMap<>();

    static {
        cityMap.put("呼和浩特市", "101");
        cityMap.put("包头市", "102");
        cityMap.put("乌兰察布市", "103");
        cityMap.put("鄂尔多斯市", "104");
        cityMap.put("巴彦淖尔市", "105");
        cityMap.put("乌海市", "106");
        cityMap.put("赤峰市", "107");
        cityMap.put("通辽市", "109");
        cityMap.put("锡林郭勒盟市", "111");
        cityMap.put("兴安盟市", "113");
        cityMap.put("阿拉善盟市", "114");
        cityMap.put("呼伦贝尔市", "108");
        cityMap.put("北京市", "110");
        cityMap.put("天津市", "130");
        cityMap.put("淄博市", "150");
        cityMap.put("滨州市", "151");
        cityMap.put("威海市", "152");
        cityMap.put("临沂市", "153");
        cityMap.put("日照市", "154");
        cityMap.put("潍坊市", "155");
        cityMap.put("东营市", "156");
        cityMap.put("枣庄市", "157");
        cityMap.put("济宁市", "158");
        cityMap.put("菏泽市", "159");
        cityMap.put("莱芜市", "160");
        cityMap.put("烟台市", "161");
        cityMap.put("青岛市", "166");
        cityMap.put("济南市", "170");
        cityMap.put("泰安市", "172");
        cityMap.put("德州市", "173");
        cityMap.put("聊城市", "174");
        cityMap.put("沧州市", "180");
        cityMap.put("唐山市", "181");
        cityMap.put("秦皇岛市", "182");
        cityMap.put("廊坊市", "183");
        cityMap.put("张家口市", "184");
        cityMap.put("邢台市", "185");
        cityMap.put("邯郸市", "186");
        cityMap.put("保定市", "187");
        cityMap.put("石家庄市", "188");
        cityMap.put("承德市", "189");
        cityMap.put("衡水市", "720");
        cityMap.put("太原市", "190");
        cityMap.put("晋中市", "191");
        cityMap.put("阳泉市", "192");
        cityMap.put("大同市", "193");
        cityMap.put("晋城市", "194");
        cityMap.put("长治市", "195");
        cityMap.put("运城市", "196");
        cityMap.put("临汾市", "197");
        cityMap.put("忻州市", "198");
        cityMap.put("朔州市", "199");
        cityMap.put("吕梁市", "200");
        cityMap.put("马鞍山市", "300");
        cityMap.put("蚌埠市", "301");
        cityMap.put("安庆市", "302");
        cityMap.put("芜湖市", "303");
        cityMap.put("六安市", "304");
        cityMap.put("合肥市", "305");
        cityMap.put("阜阳市", "306");
        cityMap.put("淮南市", "307");
        cityMap.put("铜陵市", "308");
        cityMap.put("巢湖市", "309");
        cityMap.put("宣城市", "311");
        cityMap.put("滁州市", "312");
        cityMap.put("宿州市", "313");
        cityMap.put("淮北市", "314");
        cityMap.put("黄山市", "316");
        cityMap.put("池州市", "317");
        cityMap.put("亳州市", "318");
        cityMap.put("上海市", "310");
        cityMap.put("无锡市", "330");
        cityMap.put("南京市", "340");
        cityMap.put("镇江市", "343");
        cityMap.put("连云港市", "346");
        cityMap.put("盐城市", "348");
        cityMap.put("宿迁市", "349");
        cityMap.put("徐州市", "350");
        cityMap.put("淮安市", "354");
        cityMap.put("南通市", "358");
        cityMap.put("扬州市", "430");
        cityMap.put("常州市", "440");
        cityMap.put("泰州市", "445");
        cityMap.put("苏州市", "450");
        cityMap.put("杭州市", "360");
        cityMap.put("湖州市", "362");
        cityMap.put("嘉兴市", "363");
        cityMap.put("舟山市", "364");
        cityMap.put("绍兴市", "365");
        cityMap.put("金华市", "367");
        cityMap.put("宁波市", "370");
        cityMap.put("衢州市", "468");
        cityMap.put("丽水市", "469");
        cityMap.put("温州市", "470");
        cityMap.put("台州市", "476");
        cityMap.put("福州市", "380");
        cityMap.put("龙岩市", "384");
        cityMap.put("莆田市", "385");
        cityMap.put("宁德市", "386");
        cityMap.put("南平市", "387");
        cityMap.put("三明市", "389");
        cityMap.put("厦门市", "390");
        cityMap.put("漳州市", "395");
        cityMap.put("泉州市", "480");
        cityMap.put("海口市", "501");
        cityMap.put("琼海市", "504");
        cityMap.put("文昌市", "505");
        cityMap.put("万宁市", "508");
        cityMap.put("定安市", "509");
        cityMap.put("澄迈市", "511");
        cityMap.put("屯昌市", "519");
        cityMap.put("琼中市", "514");
        cityMap.put("三亚市", "502");
        cityMap.put("乐东市", "516");
        cityMap.put("陵水市", "513");
        cityMap.put("保亭市", "515");
        cityMap.put("五指山市", "507");
        cityMap.put("儋州市", "503");
        cityMap.put("东方市", "506");
        cityMap.put("临高市", "512");
        cityMap.put("昌江市", "517");
        cityMap.put("白沙市", "518");
        cityMap.put("广州市", "510");
        cityMap.put("湛江市", "520");
        cityMap.put("汕尾市", "525");
        cityMap.put("揭阳市", "526");
        cityMap.put("梅州市", "528");
        cityMap.put("佛山市", "530");
        cityMap.put("潮州市", "531");
        cityMap.put("清远市", "535");
        cityMap.put("肇庆市", "536");
        cityMap.put("云浮市", "538");
        cityMap.put("深圳市", "540");
        cityMap.put("江门市", "550");
        cityMap.put("中山市", "556");
        cityMap.put("韶关市", "558");
        cityMap.put("汕头市", "560");
        cityMap.put("阳江市", "565");
        cityMap.put("茂名市", "568");
        cityMap.put("惠州市", "570");
        cityMap.put("东莞市", "580");
        cityMap.put("珠海市", "620");
        cityMap.put("河源市", "670");
        cityMap.put("贺州市", "588");
        cityMap.put("贵港市", "589");
        cityMap.put("防城港市", "590");
        cityMap.put("南宁市", "591");
        cityMap.put("桂林市", "592");
        cityMap.put("柳州市", "593");
        cityMap.put("梧州市", "594");
        cityMap.put("玉林市", "595");
        cityMap.put("百色市", "596");
        cityMap.put("钦州市", "597");
        cityMap.put("河池市", "598");
        cityMap.put("北海市", "599");
        cityMap.put("崇左市", "600");
        cityMap.put("来宾市", "601");
        cityMap.put("香港市", "610");
        cityMap.put("西宁市", "700");
        cityMap.put("海东市", "701");
        cityMap.put("格尔木市", "702");
        cityMap.put("海西州市", "704");
        cityMap.put("海南州市", "705");
        cityMap.put("海北州市", "706");
        cityMap.put("黄南州市", "707");
        cityMap.put("果洛州市", "708");
        cityMap.put("玉树州市", "709");
        cityMap.put("武汉市", "710");
        cityMap.put("宜昌市", "711");
        cityMap.put("荆州市", "712");
        cityMap.put("仙桃市", "713");
        cityMap.put("黄冈市", "714");
        cityMap.put("黄石市", "715");
        cityMap.put("襄阳市", "716");
        cityMap.put("孝感市", "717");
        cityMap.put("鄂州市", "718");
        cityMap.put("咸宁市", "719");
        cityMap.put("十堰市", "721");
        cityMap.put("随州市", "723");
        cityMap.put("荆门市", "724");
        cityMap.put("天门市", "725");
        cityMap.put("潜江市", "726");
        cityMap.put("恩施市", "727");
        cityMap.put("浏阳市", "746");
        cityMap.put("长沙市", "741");
        cityMap.put("株洲市", "742");
        cityMap.put("湘潭市", "743");
        cityMap.put("衡阳市", "744");
        cityMap.put("岳阳市", "745");
        cityMap.put("益阳市", "747");
        cityMap.put("郴州市", "748");
        cityMap.put("常德市", "749");
        cityMap.put("娄底市", "791");
        cityMap.put("邵阳市", "792");
        cityMap.put("湘西市", "793");
        cityMap.put("张家界市", "794");
        cityMap.put("怀化市", "795");
        cityMap.put("永州市", "796");
        cityMap.put("景德镇市", "740");
        cityMap.put("南昌市", "750");
        cityMap.put("吉安市", "751");
        cityMap.put("赣州市", "752");
        cityMap.put("新余市", "753");
        cityMap.put("鹰潭市", "754");
        cityMap.put("九江市", "755");
        cityMap.put("宜春市", "756");
        cityMap.put("上饶市", "757");
        cityMap.put("萍乡市", "758");
        cityMap.put("抚州市", "759");
        cityMap.put("郑州市", "760");
        cityMap.put("洛阳市", "761");
        cityMap.put("开封市", "762");
        cityMap.put("焦作市", "763");
        cityMap.put("新乡市", "764");
        cityMap.put("许昌市", "765");
        cityMap.put("漯河市", "766");
        cityMap.put("安阳市", "767");
        cityMap.put("商丘市", "768");
        cityMap.put("平顶山市", "769");
        cityMap.put("周口市", "770");
        cityMap.put("驻马店市", "771");
        cityMap.put("三门峡市", "772");
        cityMap.put("濮阳市", "773");
        cityMap.put("鹤壁市", "774");
        cityMap.put("济源市", "775");
        cityMap.put("信阳市", "776");
        cityMap.put("南阳市", "777");
        cityMap.put("拉萨市", "790");
        cityMap.put("日喀则市", "797");
        cityMap.put("山南市", "798");
        cityMap.put("林芝市", "799");
        cityMap.put("昌都市", "800");
        cityMap.put("那曲市", "801");
        cityMap.put("阿里市", "802");
        cityMap.put("成都市", "810");
        cityMap.put("雅安市", "811");
        cityMap.put("凉山彝族自治州市", "812");
        cityMap.put("攀枝花市", "813");
        cityMap.put("乐山市", "814");
        cityMap.put("泸州市", "815");
        cityMap.put("内江市", "816");
        cityMap.put("宜宾市", "817");
        cityMap.put("自贡市", "818");
        cityMap.put("眉山市", "819");
        cityMap.put("达州市", "820");
        cityMap.put("遂宁市", "821");
        cityMap.put("南充市", "822");
        cityMap.put("广安市", "823");
        cityMap.put("绵阳市", "824");
        cityMap.put("德阳市", "825");
        cityMap.put("广元市", "826");
        cityMap.put("巴中市", "827");
        cityMap.put("甘孜藏族自治州市", "828");
        cityMap.put("阿坝藏族羌族自治州市", "829");
        cityMap.put("资阳市", "830");
        cityMap.put("重庆市", "831");
        cityMap.put("宝鸡市", "840");
        cityMap.put("西安市", "841");
        cityMap.put("延安市", "842");
        cityMap.put("渭南市", "843");
        cityMap.put("咸阳市", "844");
        cityMap.put("榆林市", "845");
        cityMap.put("铜川市", "846");
        cityMap.put("商洛市", "847");
        cityMap.put("安康市", "848");
        cityMap.put("汉中市", "849");
        cityMap.put("铜仁市", "785");
        cityMap.put("黔东南市", "786");
        cityMap.put("遵义市", "787");
        cityMap.put("黔南市", "788");
        cityMap.put("安顺市", "789");
        cityMap.put("贵阳市", "850");
        cityMap.put("毕节市", "851");
        cityMap.put("黔西南市", "852");
        cityMap.put("六盘水市", "853");
        cityMap.put("景洪市", "868");
        cityMap.put("德宏市", "730");
        cityMap.put("保山市", "731");
        cityMap.put("文山市", "732");
        cityMap.put("临沧市", "733");
        cityMap.put("怒江市", "734");
        cityMap.put("迪庆市", "735");
        cityMap.put("西双版纳市", "736");
        cityMap.put("昆明市", "860");
        cityMap.put("红河市", "861");
        cityMap.put("大理市", "862");
        cityMap.put("丽江市", "863");
        cityMap.put("楚雄市", "864");
        cityMap.put("玉溪市", "865");
        cityMap.put("曲靖市", "866");
        cityMap.put("昭通市", "867");
        cityMap.put("思茅市", "869");
        cityMap.put("兰州市", "870");
        cityMap.put("定西市", "871");
        cityMap.put("平凉市", "872");
        cityMap.put("庆阳市", "873");
        cityMap.put("武威市", "874");
        cityMap.put("张掖市", "875");
        cityMap.put("嘉峪关市", "876");
        cityMap.put("天水市", "877");
        cityMap.put("临夏市", "878");
        cityMap.put("白银市", "879");
        cityMap.put("金昌市", "930");
        cityMap.put("酒泉市", "931");
        cityMap.put("陇南市", "960");
        cityMap.put("甘南市", "961");
        cityMap.put("银川市", "880");
        cityMap.put("吴忠市", "883");
        cityMap.put("石嘴山市", "884");
        cityMap.put("固原市", "885");
        cityMap.put("中卫市", "886");
        cityMap.put("乌鲁木齐市", "890");
        cityMap.put("昌吉市", "891");
        cityMap.put("奎屯市", "892");
        cityMap.put("石河子市", "893");
        cityMap.put("吐鲁番市", "894");
        cityMap.put("巴州市", "895");
        cityMap.put("阿克苏市", "896");
        cityMap.put("喀什市", "897");
        cityMap.put("伊犁市", "898");
        cityMap.put("克拉玛依市", "899");
        cityMap.put("哈密市", "900");
        cityMap.put("博乐市", "951");
        cityMap.put("塔城市", "952");
        cityMap.put("阿勒泰市", "953");
        cityMap.put("克州市", "954");
        cityMap.put("和田市", "955");
        cityMap.put("长春市", "901");
        cityMap.put("吉林市", "902");
        cityMap.put("四平市", "903");
        cityMap.put("松原市", "904");
        cityMap.put("通化市", "905");
        cityMap.put("辽源市", "906");
        cityMap.put("白城市", "907");
        cityMap.put("白山市", "908");
        cityMap.put("延边市", "909");
        cityMap.put("沈阳市", "910");
        cityMap.put("铁岭市", "911");
        cityMap.put("鞍山市", "912");
        cityMap.put("抚顺市", "913");
        cityMap.put("本溪市", "914");
        cityMap.put("丹东市", "915");
        cityMap.put("锦州市", "916");
        cityMap.put("营口市", "917");
        cityMap.put("阜新市", "918");
        cityMap.put("辽阳市", "919");
        cityMap.put("朝阳市", "920");
        cityMap.put("盘锦市", "921");
        cityMap.put("葫芦岛市", "922");
        cityMap.put("大连市", "940");
        cityMap.put("哈尔滨市", "971");
        cityMap.put("齐齐哈尔市", "973");
        cityMap.put("佳木斯市", "976");
        cityMap.put("大庆市", "981");
        cityMap.put("牡丹江市", "988");
        cityMap.put("绥化市", "989");
        cityMap.put("黑河市", "990");
        cityMap.put("鸡西市", "991");
        cityMap.put("七台河市", "992");
        cityMap.put("鹤岗市", "993");
        cityMap.put("双鸭山市", "994");
        cityMap.put("大兴安岭市", "995");
        cityMap.put("伊春市", "996");
    }
}

19.数据库操作类配置

  1. 上依赖
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
            <scope>compile</scope>
        </dependency>
  1. 配置文件链接数据库配置
    在这里插入图片描述
  2. 建立dao业务层
package com.dao;

import com.BannerDTO;
import org.apache.ibatis.annotations.Mapper;
import java.util.Date;

@Mapper
public interface BannerDao {

    /**
     * 查询时间符合并且已上架的banner
     * @param currentTime 当前时间
     * @return banner
     */
    BannerDTO queryPropagandaBanner(Date currentTime);
}

4.配置sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
		PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.BannerDao">

	<resultMap id="resultMap" type="com.BannerDTO">
		<id column="ID" property="id"/>
		<result column="BANNER_TEMPLATE" property="bannerTemplate"/>
		<result column="BANNER_NAME" property="bannerName"/>
		<result column="BANNER_POSITION" property="bannerPosition"/>
		<result column="BEGIN_TIME" property="beginTime"/>
		<result column="END_TIME" property="endTime"/>
		<result column="STATE" property="state"/>
		<result column="CREATER" property="creater"/>
		<result column="CREATER_TIME" property="createrTime"/>
		<result column="UPDATED_BY" property="updatedBy"/>
		<result column="UPDATED_BY_TIME" property="updatedByTime"/>
	</resultMap>

	<select id="queryPropagandaBanner" resultMap="resultMap">
		SELECT
		ID,
		BANNER_TEMPLATE,
		BANNER_NAME,
		BANNER_POSITION,
		BEGIN_TIME,
		END_TIME
		FROM
		SF_BANNER
		WHERE
		((BEGIN_TIME &lt;= #{currentTime} AND END_TIME &gt;= #{currentTime}) OR (BEGIN_TIME &lt;= #{currentTime} AND (END_TIME IS NULL OR LENGTH(TRIM(END_TIME)) = 0)))
		AND STATE = '20'
	</select>

</mapper>

20. NumberUtils(字符串转换,null设默认值)

package org.apache.commons.lang.math;
/**
         * @方法: public static int toInt(String str)
         * @作用: 将一个字符串转换成int类型
         * @参数: str-将要转换的字符串,可能会是null
         * @返回值: 转换失败返回0,否则返回转换的结果值
         */
        System.out.println(NumberUtils.toInt("5")); //返回5
        System.out.println(NumberUtils.toInt("")); //返回0
        System.out.println(NumberUtils.toInt(null)); //返回0
 
        /**
         * @方法: public static int toInt(String str, int defaultValue)
         * @作用: 将一个字符串转换成int类型,如果转换失败就返回一个默认值defaultValue
         * @参数: str-将要转换的字符串,可能会是null;
         *        defaultValue-默认值,如果转换失败就显示默认值
         * @返回值: 如果转换失败就返回一个默认值defaultValue,否则返回转换的结果值
         */
        System.out.println(NumberUtils.toInt(null, 0)); // 返回 0
        System.out.println(NumberUtils.toInt("", 0)); // 返回 0
        System.out.println(NumberUtils.toInt("5", 0)); // 返回 5
 
        /**
         * @方法: public static long toLong(String str)
         * @作用: 将一个字符串数据转换成一个long类型数据,如果转换失败返回0
         * @参数: 转换的字符串,可能为null;
         * @返回值: 字符串代表的long数据类型,或者转换失败的默认值0
         */
        System.out.println(NumberUtils.toLong(null)); // 返回 0
        System.out.println(NumberUtils.toLong("6")); // 返回 6
        System.out.println(NumberUtils.toLong("")); // 返回 0
 
        /**
         * @方法: public static long toLong(String str, long defaultValue)
         * @作用: 将一个字符串数据转换成一个long类型数据,如果转换失败返回默认值
         * @参数: str-转换的字符串,可能为null;
         *        defaultValue-默认值
         * @返回值: 字符串代表的long数据类型,转换失败的时候返回默认值
         */
        System.out.println(NumberUtils.toLong(null, 0)); // 返回 0
        System.out.println(NumberUtils.toLong("6", 0)); // 返回 6
        System.out.println(NumberUtils.toLong("", 0)); // 返回 0
 
        //double(双精度浮点数)和float(单精度浮点数):
        //在内存中占的字节数不同,单精度浮点数占4个字节,双精度浮点数占8个字节;
        //有效位数不同,单精度浮点数有效位数是8位,双精度浮点数有效位数是16位;
        //位数不同,单精度浮点的表示范围:-3.40E+38 ~ +3.40E+38,双精度浮点的表示范围:-1.79E+308 ~ +1.79E+308
        //处理速度不同,一般来说处理器处理单精度浮点数的速度比处理双精度的浮点数速度要快;
 
        /**
         * @方法: public static double toDouble(String str)
         * @作用: 将一个字符串转换成double类型
         * @参数: str-转换的字符串,可能为null
         * @返回值: 字符串代表的double值;如果转换失败返回0.0d,如果字符串是null返回0.0d
         */
        System.out.println(NumberUtils.toDouble(null)); // 返回 0.0
        System.out.println(NumberUtils.toDouble("")); // 返回 0.0
        System.out.println(NumberUtils.toDouble("12")); // 返回 12.0
 
        /**
         * @方法: public static double toDouble(String str, double defaultValue)
         *
         * @作用: 将一个字符串转换成double类型,如果转换失败将会把默认值defaultValue返回
         * @参数: str-转换的字符串,可能为null;
         *        defaultValue-默认值
         * @返回值: 转换成功返回字符串代表的double数据类型;如果转换失败返回0.0d;如果字符串值是null将会把默认值返回
         */
        System.out.println(NumberUtils.toDouble(null, 0.001d)); // 返回 0.001
        System.out.println(NumberUtils.toDouble("", 0.001d)); // 返回 0.001
        System.out.println(NumberUtils.toDouble("12", 0.001d)); // 返回 12.0
 
        /**
         * @方法: public static float toFloat(String str)
         * @作用: 将一个字符串转换成float数据类型,如果转型失败返回0.0f;如果传入参数字符串为null,返回默认值0
         * @参数: str-转换的字符串,可能为null
         * @返回值: 转换成功返回字符串代表的float数据类型,如果转型失败返回0
         */
        System.out.println(NumberUtils.toFloat(null)); // 返回 0
        System.out.println(NumberUtils.toFloat("")); // 返回 0
        System.out.println(NumberUtils.toFloat("1.6")); // 返回 1.6
 
        /**
         * @方法: public static float toFloat(String str, float defaultValue)
         * @作用: 将一个字符串转换成float数据类型
         * @参数: str-转换的字符串,可能为null
         *        defaultValue-默认值
         * @返回值: 转换成功返回字符串代表的float数据类型,否则返回默认值defaultValue
         *          (如果转型失败返回默认值defaultValue;如果传入参数字符串为null,返回默认值defaultValue)
         */
        System.out.println(NumberUtils.toFloat(null, 0.0001f)); // 返回 1.0E-4(1.0 * 10^﹣4)
        System.out.println(NumberUtils.toFloat("",0.001f)); // 返回 0.001
        System.out.println(NumberUtils.toFloat("1.6",0.0001f)); // 返回 1.6
 
 
        /**
         * @方法: public static boolean isDigits(String str)
         * @作用: 检查字符串是否是只包含数字字符,null和空将会返回false
         * @参数: str-检查的字符串 str可为null
         * @返回值: 只包含数字返回true,否则返回false
         */
        System.out.println(NumberUtils.isDigits("6666! Life is so short,do something to make yourself happy,such as coding! 6666")); // 返回 false
        System.out.println(NumberUtils.isDigits("6666!生活如此短暂,做一些使自己开心的事,比如编程!6666"));  // 返回 false
        System.out.println(NumberUtils.isDigits("666666"));  // 返回 true
 
        /**
         * @方法: public static boolean isParsable(String str)
         * @作用: 检验提供的字符串是否可以转换为number,
         *        可解析的number包括下面的方法 Integer.parseInt(String), Long.parseLong(String),
         *        Float.parseFloat(String) or Double.parseDouble(String),
         *        当调用上面的方法时这个方法可以替代ParseException异常;十六进制和科学符号被认为是不可解析的;null和空字符串返回false;
         * @参数: str-检验的字符串 str可为null
         * @返回值: true-如果参数是可转换的字符串,否则返回false
         */
        System.out.println(NumberUtils.isParsable(""));  // 返回 false
        System.out.println(NumberUtils.isParsable(null));  // 返回 false
        System.out.println(NumberUtils.isParsable("12"));  // 返回 true
        System.out.println(NumberUtils.isParsable("12.0")); // 返回 true
        System.out.println(NumberUtils.isParsable("12.3")); // 返回 true
        System.out.println(NumberUtils.isParsable("7a"));  // 返回 false (十六进制7a对应十进制122)
        System.out.println(NumberUtils.isParsable("1.0E-4")); // 返回 false
 
 
        /**
         * @方法: public static boolean isCreatable(String str)
         * @作用: 检查字符串是否是一个有效的number;
         *        有效数字包括进制标有0x或0X预选项,八进制数、科学记数法和标有类型限定符的数字,
         *        以 前导零开头的非十六进制字符串被视为八进制值,因此字符串09将返回false,因为9不是有效的八进制,
         *        然而从0开始的数字,被视为十进制;null、空或者空串将返回false;
         * @参数: str-检查的字符串; str可为null
         * @返回值: true-如果字符串是一个正确格式化的数字,否则返回false
         */
        System.out.println(NumberUtils.isCreatable(null)); // 返回 false
        System.out.println(NumberUtils.isCreatable(" ")); // 返回 false
        System.out.println(NumberUtils.isCreatable("")); // 返回 false
        System.out.println(NumberUtils.isCreatable("09")); // 返回 false
        System.out.println(NumberUtils.isCreatable("9")); // 返回 true
        System.out.println(NumberUtils.isCreatable("0x56")); // 返回 true
        System.out.println(NumberUtils.isCreatable("0X20")); // 返回 true
 
        /**
         * @方法: public static int compare(int x, int y)
         * @作用: 比较两个int数值
         * @参数: x-第一个int比较值,y-第二个int比较值
         * @返回值: 如果 x==y 返回0;x<y 返回负数(-1);x>y 返回正数(1)
         */
        System.out.println(NumberUtils.compare(1,1)); // 返回 0
        System.out.println(NumberUtils.compare(1,2)); // 返回 -1
        System.out.println(NumberUtils.compare(3,2)); // 返回 1
 
        /**
         * @方法: public static int compare(long x, long y)
         * @作用: 比较两个int数值
         * @参数: x-第一个long比较值,y-第二个long比较值
         * @返回值: 如果 x==y 返回0;x<y 返回负数(-1);x>y 返回正数(1)
         */
        System.out.println(NumberUtils.compare(1L,1L)); // 返回 0
        System.out.println(NumberUtils.compare(3L,2L)); // 返回 1
        System.out.println(NumberUtils.compare(5L,6L)); // 返回 -1
 
        /**
         * @方法: public static BigDecimal createBigDecimal(String str)
         * @作用: 将一个字符串转换成BigDecimal类型,如果字符串是null将会返回null
         * @参数: str-转换的字符串,可能为null
         * @返回值: 被转换的BigDecimal;如果输入的字符串是null将会返回null
         * @抛出异常: 空串或不能解析将会抛出 NumberFormatException
         */
//        System.out.println(NumberUtils.createBigDecimal("abc")); // 报异常 java.lang.NumberFormatException
//        System.out.println(NumberUtils.createBigDecimal("")); // 报异常 java.lang.NumberFormatException: A blank string is not a valid number
        System.out.println(NumberUtils.createBigDecimal(null)); // 返回 null
        System.out.println(NumberUtils.createBigDecimal("1235")); // 返回 1235
 
        /**
         * @方法: public static Double createDouble(String str)
         * @作用: 将一个字符串转换成Double类型,如果输入字符串是null将会返回null
         * @参数: str-转换的字符串,可能为null;
         * @返回值: 被转换的Double值(如果输入字符串是null将会返回null);
         * @抛出异常: 如果值不能解析将会抛出NumberFormatException ;
         */
        System.out.println(NumberUtils.createDouble(null)); // 返回 null
//        System.out.println(NumberUtils.createDouble("asc")); // 返回 java.lang.NumberFormatException: For input string: "asc"
        System.out.println(NumberUtils.createDouble("12")); // 返回 12.0
 
        /**
         * @方法: public static Long createLong(String str)
         * @作用: 将一个字符串转换为Long数据类型,注:前导零表示八进制;空间不剪裁。如果字符串值是null将会返回null;
         * @参数: str-转换的字符串,可能为null;
         * @返回值: 被转换的Long数据(如果输入的是null将返回null);
         * @抛出异常: 如果值不能被转换将会抛出NumberFormatException异常;
         */
//        System.out.println(NumberUtils.createLong("")); // java.lang.NumberFormatException: Zero length string
        System.out.println(NumberUtils.createLong(null));  // 返回 null
        System.out.println(NumberUtils.createLong("123")); // 返回 123
 
        /**
         * @方法: public static BigInteger createBigInteger(String str)
         * @作用: 将一个字符串转换为BigDecimal类型,自3.2以来,它处理六(0x或#)和八进制(0)符号。如果字符串为null将会返回null
         * @参数: str-转换的字符串,可能为null
         * @返回参数: 被转换的BigDecimal[如果输入字符串为null将返回null]
         * @抛出异常: 如果值不能被转换将会抛出NumberFormatException异常
         */
//        System.out.println(NumberUtils.createBigInteger("")); // java.lang.NumberFormatException: Zero length BigInteger
        System.out.println(NumberUtils.createBigInteger(null)); // 返回 null
//        System.out.println(NumberUtils.createBigInteger("12s"));// java.lang.NumberFormatException: For input string: "12s"
        System.out.println(NumberUtils.createBigInteger("12")); // 返回 12
 
        /**
         * @方法: public static Number createNumber(String str)
         * @作用: 将一个字符串值转换为java.lang.Number类型
         * @参数: str-转换字符串,可能为null
         * @返回值: 从字符串创建的Number值;如果输入的字符串为null则返回null
         * @抛出异常: 如果值不能被转换将会抛出NumberFormatException异常
         */
        System.out.println(NumberUtils.createNumber("123")); // 返回 123
//        System.out.println(NumberUtils.createNumber("12s")); // 返回 java.lang.NumberFormatException: 12s is not a valid number
        System.out.println(NumberUtils.createNumber("123.0")); // 返回 123.0
//        System.out.println(NumberUtils.createNumber("")); // 返回 java.lang.NumberFormatException: A blank string is not a valid number
        System.out.println(NumberUtils.createNumber(null)); // 返回 null
 
        /**
         * @方法: public static int max(int a, int b, int c)
         * @作用: 获取三个int值中最大的一个
         * @参数: a-值1,b-值2,c-值3
         * @返回值: 最大的值
         * @抛出异常: 如果参数是空抛出java.lang.IllegalArgumentException: Array cannot be empty
         */
        System.out.println(NumberUtils.max(1,5,2,9,10)); // 返回 10
//        System.out.println(NumberUtils.max()); // 返回 java.lang.IllegalArgumentException: Array cannot be empty
 
        /**
         * @方法: public static int max(int… array)
         * @作用: 返回数组中最大的值
         * @参数: array-一定不能为空或者null
         * @返回值: 数组中最大的值
         * @抛出异常: 如果数组为空或者null将会抛出IllegalArgumentException异常
         */
        System.out.println(NumberUtils.max(1,2,3,4,5,9,1.0,2.0,2.5,9.8)); //  返回 9.8

21 double去除多余的尾0

toString:转换成科学计数法
toPlainString:正常去0后显示

 public static void main(String[] args) {

        System.out.println(changePrice("1111.005"));
        System.out.println(changePrice("1111.0000"));
        System.out.println(changePrice("12.00"));
        System.out.println(changePrice("111111"));
        System.out.println(changePrice("11111111"));
        System.out.println(changePrice("1.00870"));
    }
    public static String changePrice (String price){
        BigDecimal bigDecimalAP = new BigDecimal(price);
        return bigDecimalAP.stripTrailingZeros().toPlainString();
    }

22.Java8之list.stream的常见使用

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version>
        </dependency>
 
 
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

在这里插入图片描述

public static void main(String[] args) {
        List<Student> list = Lists.newArrayList();
        list.add(new Student("测试", "男", 18));
        list.add(new Student("开发", "男", 20));
        list.add(new Student("运维", "女", 19));
        list.add(new Student("DBA", "女", 22));
        list.add(new Student("运营", "男", 24));
        list.add(new Student("产品", "女", 21));
        list.add(new Student("经理", "女", 25));
        list.add(new Student("产品", "女", 21));
 
        //求性别为男的学生集合
        List<Student> l1 = list.stream().filter(student -> student.sex.equals("男")).collect(toList());
        
        //map的key值true为男,false为女的集合
        Map<Boolean, List<Student>> map = list.stream().collect(partitioningBy(student -> student.getSex().equals("男")));
 
        //求性别为男的学生总岁数
        Integer sum = list.stream().filter(student -> student.sex.equals("男")).mapToInt(Student::getAge).sum();
 
        //按性别进行分组统计人数
        Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(Student::getSex, Collectors.summingInt(p -> 1)));
 
        //判断是否有年龄大于25岁的学生
        boolean check = list.stream().anyMatch(student -> student.getAge() > 25);
 
        //获取所有学生的姓名集合
        List<String> l2 = list.stream().map(Student::getName).collect(toList());
 
        //求所有人的平均年龄
        double avg = list.stream().collect(averagingInt(Student::getAge));
 
        //求年龄最大的学生
        Student s = list.stream().reduce((student, student2) -> student.getAge() > student2.getAge() ? student:student2).get();
        
        Student stu = list.stream().collect(maxBy(Comparator.comparing(Student::getAge))).get();
 
        //按照年龄从小到大排序
        List<Student> l3 = list.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(toList());
 
        //求年龄最小的两个学生
        List<Student> l4 = l3.stream().limit(2).collect(toList());
 
        //获取所有的名字,组成一条语句
        String str = list.stream().map(Student::getName).collect(Collectors.joining(",", "[", "]"));
        
        //获取年龄的最大值、最小值、平均值、求和等等
        IntSummaryStatistics intSummaryStatistics = list.stream().mapToInt(Student::getAge).summaryStatistics();
        System.out.println(intSummaryStatistics.getMax());
        System.out.println(intSummaryStatistics.getCount());
    }
 
    @Data
    @AllArgsConstructor
    static class Student{
        String name;
        String sex;
        Integer age;
 
    }

最后给大家说一个并行化流操作parallelStream(),跟stream()的用法一样。使用parallelStream就能立即获得一个拥有并行能力的流,利用好并行化非常重要。不过并不是所有的流计算都要使用并行化流操作,只有当计算机是多核并且集合数据量较大(超过一万)的时候使用并行化流操作可以提高效率。

影响性能的五要素:数据大小、源数据结构、值是否装箱、可用的CPU数量以及处理每个元素所花的时间。

							//1:价格升序 ,2:价格降序 
							String sortOut = jsonObject.getString("sortOut");
							if(StringUtils.equals("1",sortOut)){
								physicalGoodsVos = physicalGoodsVos.stream().sorted(Comparator.comparing(PhysicalGoodsVo::getShopPriceSort)).collect(Collectors.toList());
							}else if(StringUtils.equals("2",sortOut)){
								physicalGoodsVos = physicalGoodsVos.stream().sorted(Comparator.comparing(PhysicalGoodsVo::getShopPriceSort).reversed()).collect(Collectors.toList());
							}

23.n位随机数生成

例如以下是六位随机数生成

(int)(100000 + Math.random() * (999999 - 100000 +1)

当然使用工具:RandomUtil.getRand(6)更简单

24.数组和list互转

	// List 转 数组
	String[] strArr = {"apple","pear","banana","peach"};
	List<String> list = Arrays.asList(strArr);
	// 数组 转 List
	String[] arr = (String[]) list.toArray();

25.base64urlsafestr加解密

parameter=base64urlsafestr(aes256(requestjson))
encprikey=base64urlsafestr(RSA(KEY))
sign=base64urlsafestr(sign(content),privateKey)

package com.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERInteger;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;


public class EquityCoreUtils {

    /**
     * 生成256bits的AES加密方式key
     * @param length  bits位
     * @return
     * @throws Exception
     */
    public static byte[] generateAesKey(int length) throws Exception {
        KeyGenerator keyGenerator = null;
        keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(length);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] key = secretKey.getEncoded();
        return key;
    }

    /**
     * 基于base64编码方式加密
     * Base64:基于64个可打印的字符来表示二进制的数据的一种方法
     * @param secretKey 256位符合AES加密方式的key
     * @param content 加密内容
     * @return
     * @throws Exception
     */
    public static String encrypt(byte[] secretKey, String content) throws Exception {
        try {
            SecretKey key = new SecretKeySpec(secretKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] byte_encode = content.getBytes("utf-8");
            byte[] byte_AES = cipher.doFinal(byte_encode);
            String encryptContent = new String(Base64.encodeBase64URLSafeString(byte_AES));
            return encryptContent;
        } catch (Exception e) {
            throw e;
        }
    }

    public static String decrypt(String encryptCode, byte[] secretKey) throws Exception{
        try {
            SecretKey key = new SecretKeySpec(secretKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] byteContent = Base64.decodeBase64(encryptCode.getBytes("utf-8"));
            byte[] byteDecode = cipher.doFinal(byteContent);
            String aesDecode = new String(byteDecode, "utf-8");
            return aesDecode;
        } catch (Exception e) {
            throw e;
        }
    }

    public static byte[] rsaEncrypt(String key, byte[] content) throws Exception {
        byte[] result = encryption(1,
                key.getBytes("UTF-8"), true,
                content);
        return result;
    }

    public static byte[] encryption(int type, byte[] key, boolean bEncryption, byte[] inData) {
        byte[] signaturepem;
        if (!bEncryption) {
            signaturepem = checkPEM(inData);
            if (signaturepem != null) {
                inData = org.bouncycastle.util.encoders.Base64.decode(signaturepem);
            }
        }
        signaturepem = checkPEM(key);
        if (signaturepem != null) {
            key = org.bouncycastle.util.encoders.Base64.decode(signaturepem);
        }

        String alg = "";
        if (type == 1) {
            alg = "RSA/ECB/PKCS1Padding";
        } else {
            alg = "RSA/ECB/NoPadding";
        }
        byte[] outdata = crypto(alg, key, bEncryption, inData);
        return outdata;
    }

    public static byte[] checkPEM(byte[] src) {
        String charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/+= \r\n-";
        for (int i = 0; i < src.length; ++i) {
            if (charset.indexOf(src[i]) == -1) {
                return null;
            }
        }
        StringBuffer sb = new StringBuffer(src.length);
        String xx = new String(src);
        for (int i = 0; i < xx.length(); ++i) {
            if (xx.charAt(i) != ' ' && xx.charAt(i) != '\r' && xx.charAt(i) != '\n') {
                sb.append(xx.charAt(i));
            }
        }
        return sb.toString().getBytes();
    }

    public static byte[] crypto(String alg, byte[] keyDERString, boolean bEncrypto, byte[] inData) {
        try {
            Cipher cipher = Cipher.getInstance(alg);
            int blockSize;
            int outputSize;
            byte[] processAfter;
            if (bEncrypto) {
                RSAPublicKey publickey = null;
                try {
                    publickey = getPublicKey(keyDERString);
                } catch (Exception var9) {
//                    throw new CrypException(-2147483640, "A error input key! " + var9.getMessage());
                }

                cipher.init(1, publickey);
                blockSize = cipher.getBlockSize();
                outputSize = cipher.getOutputSize(blockSize);
                processAfter = new byte[outputSize];
                processAfter = cipher.doFinal(inData);
                return processAfter;
            } else {
                RSAPrivateKey privatekey = null;
                try {
                    privatekey = getRPKS(keyDERString);
                } catch (Exception var10) {
//                    throw new CrypException(-2147483640, "A error input key! " + var10.getMessage());
                }

                cipher.init(2, privatekey);
                blockSize = cipher.getBlockSize();
                outputSize = cipher.getOutputSize(blockSize);
                processAfter = new byte[outputSize];
                processAfter = cipher.doFinal(inData);
                return processAfter;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static RSAPrivateKey getRPKS(byte[] keyder) {
        try {
            ByteArrayInputStream bIn = new ByteArrayInputStream(keyder);
            ASN1InputStream encais = new ASN1InputStream(bIn);
            ASN1Primitive encdobj = encais.readObject();
            ASN1Sequence encass = (ASN1Sequence) encdobj;
            ASN1Integer encdermod = DERInteger.getInstance(encass.getObjectAt(1));
            BigInteger mod = encdermod.getValue();
            ASN1Integer encderexp = DERInteger.getInstance(encass.getObjectAt(2));
            BigInteger pubexp = encderexp.getValue();
            BigInteger errpriexp = DERInteger.getInstance(encass.getObjectAt(3)).getValue();
            BigInteger primeP = DERInteger.getInstance(encass.getObjectAt(4)).getValue();
            BigInteger primeQ = DERInteger.getInstance(encass.getObjectAt(5)).getValue();
            BigInteger DP = DERInteger.getInstance(encass.getObjectAt(6)).getValue();
            BigInteger DQ = DERInteger.getInstance(encass.getObjectAt(7)).getValue();
            BigInteger QmodP = DERInteger.getInstance(encass.getObjectAt(8)).getValue();
            encais.close();
            bIn.close();
            bIn = null;
            BigInteger onepar = new BigInteger("1", 16);
            BigInteger priexp = pubexp.modInverse(primeP.subtract(onepar).multiply(primeQ.subtract(onepar)));
            KeySpec prikeyspec = new RSAPrivateCrtKeySpec(mod, pubexp, priexp, primeP, primeQ, DP, DQ, QmodP);
            KeyFactory prikeyfact = KeyFactory.getInstance("RSA");
            PrivateKey prikey = prikeyfact.generatePrivate(prikeyspec);
            RSAPrivateKey rsaprivatekey1 = (RSAPrivateKey) prikey;
            return rsaprivatekey1;
        } catch (Exception var21) {
            var21.printStackTrace();
        }
        return null;
    }

    public static RSAPublicKey getPublicKey(byte[] pubkeybyte) {
        try {
            ByteArrayInputStream bIn = new ByteArrayInputStream(pubkeybyte);
            ASN1InputStream ais = new ASN1InputStream(bIn);
            ASN1Primitive dobj = ais.readObject();
            ASN1Sequence ass = (ASN1Sequence) dobj;
            ais.close();
            bIn.close();
            bIn = null;
            ASN1Integer dermod = DERInteger.getInstance(ass.getObjectAt(0));
            BigInteger mod = dermod.getValue();
            ASN1Integer derexp = DERInteger.getInstance(ass.getObjectAt(1));
            BigInteger exp = derexp.getValue();
            RSAPublicKeySpec pubkeyspec = new RSAPublicKeySpec(mod, exp);
            KeyFactory pubkeyfact = KeyFactory.getInstance("RSA");
            RSAPublicKey rsapublickey1 = (RSAPublicKey) pubkeyfact.generatePublic(pubkeyspec);
            return rsapublickey1;
        } catch (Exception var12) {
            var12.printStackTrace();
        }
        return null;
    }

    public static byte[]  sign(String originalData,String privateKey)
            throws Exception {

        byte[] signBytes = RsaSign(261, privateKey.getBytes("UTF-8"), originalData.getBytes());
        return signBytes;

    }

    public static byte[] RsaSign(int type, byte[] privateKey, byte[] indata) {
        byte[] signaturepem = checkPEM(privateKey);
        if (signaturepem != null) {
            privateKey = org.bouncycastle.util.encoders.Base64.decode(signaturepem);
        }

        String Algorithms = "";
        if (type == 257) {
            Algorithms = "MD2WITHRSA";
        } else if (type == 258) {
            Algorithms = "MD5WITHRSA";
        } else if (type == 259) {
            Algorithms = "SHA1WITHRSA";
        } else {
            Algorithms = "SHA256WITHRSA";
        }

        byte[] signdata = sign(Algorithms, privateKey, indata);
        return signdata;
    }

    public static byte[] sign(String Algorithms, byte[] keyDERString, byte[] indata) {
        RSAPrivateKey privatekey = null;
        try {
            privatekey = getRPKS(keyDERString);
        } catch (Exception var7) {
//            throw new CrypException(-2147450878, "A error input key! " + var7.getMessage());
        }

        try {
            Signature signet = Signature.getInstance(Algorithms);
            signet.initSign(privatekey);
            signet.update(indata);
            byte[] signed = signet.sign();
            return signed;
        } catch (Exception var6) {
//            throw new CrypException(-2147450878, "Sign failed! " + var6.getMessage());
        }
        return null;
    }

    public static byte[] rsaDecrypt(String key, byte[] content) throws Exception{
        byte[] result = encryption(1,
                key.getBytes("UTF-8"), false,
                content);
        return result;
    }

}

26.页面简单提交与回显

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>超五页面切换配置</title>
    <script src="${pageContext.request.contextPath}/static/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/layui/layui.all.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/layui/css/layui.css"/>
</head>
<body>

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>超五页面切换配置</legend>
</fieldset>

<form class="layui-form" action="" method="post" id="everyDayForm">
    <div class="layui-form-item">
        <label class="layui-form-label">周一</label>
        <div class="layui-input-inline">
            <input name="mon" type="text" style="width: 150%;"  lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">周二</label>
        <div class="layui-input-inline">
            <input name="tue" type="text" style="width: 150%;"  lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">周三</label>
        <div class="layui-input-inline">
            <input name="wed" type="text" style="width: 150%;"  lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">周四</label>
        <div class="layui-input-inline">
            <input name="thu" type="text" style="width: 150%;" lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">周五</label>
        <div class="layui-input-inline">
            <input name="fri" type="text" style="width: 150%;" lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">周六</label>
        <div class="layui-input-inline">
            <input name="sat" type="text" style="width: 150%;" lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">周日</label>
        <div class="layui-input-inline">
            <input name="sun" type="text" style="width: 150%;" lay-verify="required" autocomplete="off" placeholder="请输页面ID" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" id="btn" class="layui-btn" lay-submit="" lay-filter="saveBtn">保存</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<body/>

<script>
    $(document).ready(function() {
        $.ajax({
            "url":"${pageContext.request.contextPath}/everyDay/echoPage",
            "type":"post",
            "dataType":"text",
            "success":function(jsonStr) {
                $.each(JSON.parse(jsonStr), function(idx, obj) {
                    if(obj.time == "Mon"){
                        let day = document.getElementsByName("mon")[0];
                        day.value = obj.id;
                    };
                    if(obj.time == "Tue"){
                        let day = document.getElementsByName("tue")[0];
                        day.value = obj.id;
                    };
                    if(obj.time == "Wed"){
                        let day = document.getElementsByName("wed")[0];
                        day.value = obj.id;
                    }
                    if(obj.time == "Thu"){
                        let day = document.getElementsByName("thu")[0];
                        day.value = obj.id;
                    };
                    if(obj.time == "Fri"){
                        let day = document.getElementsByName("fri")[0];
                        day.value = obj.id;
                    };
                    if(obj.time == "Sat"){
                        let day = document.getElementsByName("sat")[0];
                        day.value = obj.id;
                    };
                    if(obj.time == "Sun"){
                        let day = document.getElementsByName("sun")[0];
                        day.value = obj.id;
                    }
                });
            },
            error : function(e){
               // console.log(e.status);
               // console.log(e.responseText);
            }
        });
    });

    layui.use(['form','jquery'],function (){
        var form = layui.form;
        //监听提交
        form.on('submit(saveBtn)', function(data){
            layui.$.post('${pageContext.request.contextPath}/everyDay/addNumber',data.field,function (data){
                if (data == "OK") {
                    layer.alert("保存成功");
                } else {
                    layer.alert("保存失败");
                }
            })
        });
    })

</script>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值