IOUtils
IOUtils: Apache Commons IO用来处理输入-输出流 详情介绍: https://blog.csdn.net/l2580258/article/details/89227761 添加的依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
引入的包:
import org.apache.commons.io.IOUtils;
IOUtils 提供的一些常见的方法:
closeQuietly : 它将无条件的关闭一个可被关闭的对象而不抛出任何异常 copy: 这个方法将内容按字节从一个InputStream对象复制到一个OutputStream对象,并返回复制的字节数。同样有一个方法支持从Reader对象复制到Writer对象 IOUtils.toInputStream(A ,“utf-8”): 创建一个InputStream
FileUtils
FileUtils是 commons-io包下的FileUtils 详情介绍: 连接
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
import org.apache.commons.io.FileUtils;
提供了以下的方法:
1、copyFile(File srcFile, File destFile):拷贝文件夹 2、copyDirectory(File srcDir, File destDir):拷贝目录及文件 3、deleteQuietly(File file): 删除指定文件,从不引发异常 4、deleteDirectory(File directory)递归删除目录 5、cleanDirectory(File directory):清空目录
StringUtils
StringUtils类在操作字符串是安全的,不会报空指针异常,也正因此,在操作字符串时使用StringUtils相比使用原生的String会更加安全。 详情介绍:https://blog.csdn.net/sailor125/article/details/90765202 依赖
org.apache.commons commons-lang3 3.3.2 import org.apache.commons.lang3.StringUtils; StringUtils提供的一些常见方法 1.判断字符串是否为空: isEmpty(isNotEmpty)和 isBlank(isNotBlank) isBlank:判断更严谨,包含的有空串("")、空白符(空格""," “,制表符”\t",回车符"\r","\n"等)以及null值; isEmpty:包含是空串("")和null值,不包含空白符; 2. 移除单个字符: StringUtils.remove(String str, String remove); 3.删除所有空白符: deleteWhitespace(String str) 4. 比较两个字符串:StringUtils.equals("", “”); //可以进行空置null StringUtils.equalsIgnoreCase(“ss”, “Ss”); //不区分大小写–结果是true
DateUtils
DateUtils提供了一些常用的时间相关的格式转换操作
public class DateUtils {
public static Date DATE_NOW=new Date();
public static String getFullTimeStamp(){
return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) ;
}
public static String getSimpleTimeStamp(){
return new SimpleDateFormat("yyyyMMdd").format(new Date()) ;
}
public static String getTimeStampByPattern(String pattern){
return new SimpleDateFormat(pattern).format(new Date()) ;
}
public static String getTodayStr(){
return new SimpleDateFormat("yyyy-MM-dd").format(new Date()) ;
}
public static String getDateTimeStamp(Date date){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) ;
}
public static Date getDateByString(String str){
SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date dateTime = null;
try {
dateTime = sim.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return dateTime;
}
}
JacksonUtils
通过jackson工具我们可以封装一些常用的方法。 依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.3</version>
</dependency>
JacksonUtils
public class JacksonUtils {
public static <T> String toJson(T t) throws JsonProcessingException {
return OBJECT_MAPPER.get().writeValueAsString(t);
}
public static <T> T toEntity(String json, Class<T> valueType)
throws JsonParseException, JsonMappingException, IOException {
return OBJECT_MAPPER.get().readValue(json, valueType);
}
public static <T> List<T> toList(String json, Class<? extends List> collectionClass, Class<T> elementClass)
throws JsonParseException, JsonMappingException, IOException {
JavaType javaType = OBJECT_MAPPER.get().getTypeFactory().constructCollectionType(collectionClass, elementClass);
return OBJECT_MAPPER.get().readValue(json, javaType);
}
public static <K, V> Map<K, V> toMap(String json, Class<? extends Map> mapClass, Class<K> keyClass,
Class<V> valueClass) throws JsonParseException, JsonMappingException, IOException {
JavaType javaType = OBJECT_MAPPER.get().getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
return OBJECT_MAPPER.get().readValue(json, javaType);
}
private JacksonUtils() throws IllegalAccessException {
throw new IllegalAccessException("Can't create an instance!");
}
private static final ThreadLocal<ObjectMapper> OBJECT_MAPPER = new ThreadLocal<ObjectMapper>() {
@Override
protected ObjectMapper initialValue() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
};
}
HttpUtil
HttpUtil提供了模拟post、get请求,实现跨系统的数据访问。 HttpConnectionManager: 提供http连接管理 HttpUtil :提供具体的请求方法
HttpConnectionManager
public class HttpConnectionManager {
private static final Logger logger = LoggerFactory.getLogger(HttpConnectionManager.class);
private static final int MAX_CONNECTION_SIZE = 200;
private static final int MAX_PER_ROUTE = 50;
private PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
private HttpConnectionManager(boolean isTrust) {
try {
SSLContext sslContext;
if(isTrust) {
sslContext = getSSLContextTrustAll();
} else {
sslContext = getSSLContextCertificate();
}
init(sslContext);
} catch (Exception e) {
logger.error("初始化http连接池失败: ", e);
}
}
private static final class HttpConnectionManagerHolder {
private static HttpConnectionManager httpConnectionManager = new HttpConnectionManager(true);
}
private static final class HttpsConnectionManagerHolder {
private static HttpConnectionManager httpConnectionManager = new HttpConnectionManager(false);
}
public static HttpConnectionManager getHttpClientFactory() {
return HttpConnectionManagerHolder.httpConnectionManager;
}
public static HttpConnectionManager getHttpsClientFactory() {
return HttpsConnectionManagerHolder.httpConnectionManager;
}
private void init(SSLContext sslContext) {
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolingHttpClientConnectionManager.setMaxTotal(MAX_CONNECTION_SIZE);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
}
CloseableHttpClient getHttpClient() {
return HttpClients.custom()
.setConnectionManager(poolingHttpClientConnectionManager)
.setKeepAliveStrategy(connectionKeepAliveStrategy)
.build();
}
private SSLContext getSSLContextCertificate() throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (FileInputStream inputStream = new FileInputStream(
new File("D:\\idea_workspace\\learning\\src\\main\\resources\\https\\keystore.p12"))) {
trustStore.load(inputStream, "iflytek".toCharArray());
}
return SSLContexts.custom().loadTrustMaterial(trustStore, TrustSelfSignedStrategy.INSTANCE)
.build();
}
private SSLContext getSSLContextTrustAll() throws Exception {
return new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
}
private ConnectionKeepAliveStrategy connectionKeepAliveStrategy = (response, context) -> {
final HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement headerElement = it.nextElement();
final String param = headerElement.getName();
final String value = headerElement.getValue();
if (value != null && "timeout".equalsIgnoreCase(param)) {
try {
return Long.parseLong(value) * 1000;
} catch (final NumberFormatException ignore) {
return 1;
}
}
}
return 1;
};
}
HttpUtil
请求体可以结合jaskson来实现:
public class HttpUtil {
private HttpUtil() {
}
private static final String ENCODING = "UTF-8";
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
public static String get(String url, Map<String, String> params) {
String content = "";
CloseableHttpClient httpClient = HttpConnectionManager.getHttpClientFactory().getHttpClient();
HttpGet httpGet = new HttpGet(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
return parseResult(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return content;
}
public void SubmitPost(String url,String filename1,String filename2, String filepath){
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url);
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setParameters(new BasicNameValuePair("test", "test"));
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);
HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == HttpStatus.SC_OK){
System.out.println("服务器正常响应.....");
HttpEntity resEntity = response.getEntity();
System.out.println(EntityUtils.toString(resEntity));
EntityUtils.consume(resEntity);
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.getConnectionManager().shutdown();
} catch (Exception ignore) {
}
}
}
public static String post(String url, InputStream inputStream) {
return post(url, null, new InputStreamEntity(inputStream));
}
public static String post(String url, Map<String, String> head, List<NameValuePair> pairList) throws UnsupportedEncodingException {
UrlEncodedFormEntity basicHttpEntity = new UrlEncodedFormEntity(pairList, "UTF-8");
basicHttpEntity.setContentType("application/x-www-form-urlencoded");
return post(url, null, basicHttpEntity);
}
public static String post(String url, Map<String, String> heads, String body) {
StringEntity stringEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
stringEntity.setContentType(String.valueOf(ContentType.APPLICATION_JSON));
stringEntity.setContentEncoding(ENCODING);
return post(url, heads, stringEntity);
}
public static String post(String url, String body) {
String result = "";
try {
result = post(url, null, body);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return result;
}
public static String post(String url, Map<String, String> heads, HttpEntity httpEntity) {
String resultString = "";
HttpPost httpPost = new HttpPost(url);
if (heads != null && !heads.isEmpty()) {
for (Map.Entry<String, String> entry : heads.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
httpPost.setEntity(httpEntity);
CloseableHttpClient httpClient = HttpConnectionManager.getHttpClientFactory().getHttpClient();
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
return parseResult(httpResponse);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return resultString;
}
private static String parseResult(CloseableHttpResponse closeableHttpResponse) {
String result = "";
try {
if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Header[] headers = closeableHttpResponse.getAllHeaders();
for (Header header : headers) {
System.out.println(header);
}
InputStream inputStream = closeableHttpResponse.getEntity().getContent();
result = IOUtils.toString(inputStream, ENCODING);
inputStream.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return result;
}
}
常见的工具类方法
https://blog.csdn.net/zhw864680355/article/details/100532964 提供以下常见的工具方法
- java正则表达式的匹配包括:邮箱,手机,姓名,昵称,身份证号,银行卡号等;
- 生成6位随机数;
- 对url中字符串进行编码和解码
- 获取客户端ip地址
- 获取系统当前时间
- 生成32位编码不含横线
- 生成MD5编码
- 通过身份证获取性别
- 通过身份证获取生日
- 通过身份证获取生日
- 手机号中间4位替换成星号
- 邮箱地址加星号
- 生成随机密码
package com.xiyuan.startingpoint.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.SecureRandom;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class CommonUtil {
private static SecureRandom random = new SecureRandom();
public static final Pattern MAIL_PATTERN = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
public static final Pattern MOBILE_PATTERN = Pattern.compile("^1[3|4|5|7|8][0-9]\\d{8}$");
public static final Pattern NAME_PATTERN = Pattern.compile("^[\\u4E00-\\u9FBF][\\u4E00-\\u9FBF(.|·)]{0,13}[\\u4E00-\\u9FBF]$");
public static final Pattern NICKNAME_PATTERN = Pattern.compile("^((?!\\d{5})[\\u4E00-\\u9FBF(.|·)|0-9A-Za-z_]){2,11}$");
public static final Pattern PASSWORD_PATTERN = Pattern.compile("^[\\s\\S]{6,30}$");
public static final Pattern CODE_PATTERN = Pattern.compile("^0\\d{2,4}$");
public static final Pattern POSTCODE_PATTERN = Pattern.compile("^\\d{6}$");
public static final Pattern ID_PATTERN = Pattern.compile("^\\d{6}(\\d{8}|\\d{11})[0-9a-zA-Z]$");
public static final Pattern BANK_CARD_PATTERN = Pattern.compile("^\\d{16,30}$");
public static int random() {
int x = Math.abs(random.nextInt(899999));
return x + 100000;
}
public static String urlEncoder(String url) {
if (StringUtils.isEmpty(url)) {
return null;
}
try {
return java.net.URLEncoder.encode(url, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static String urlDecoder(String url) {
if (StringUtils.isEmpty(url)) {
return null;
}
try {
return URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public static boolean validateEmail(String email) {
if (StringUtils.isEmpty(email)) {
return false;
}
Matcher m = MAIL_PATTERN.matcher(email);
return m.matches();
}
public static boolean validateMobile(String mobile) {
if (StringUtils.isEmpty(mobile)) {
return false;
}
Matcher m = MOBILE_PATTERN.matcher(mobile);
return m.matches();
}
public static boolean validateId(String idCardNumber) {
if (StringUtils.isEmpty(idCardNumber)) {
return false;
}
Matcher m = ID_PATTERN.matcher(idCardNumber);
return m.matches() && IdcardUtils.validateCard(idCardNumber);
}
public static boolean validateName(String name) {
if (StringUtils.isEmpty(name) || name.replaceAll("[^.·]", "").length() > 1) {
return false;
}
Matcher m = NAME_PATTERN.matcher(name);
return m.matches();
}
public static boolean validateNickname(String nickname) {
if (StringUtils.isEmpty(nickname) || nickname.replaceAll("[^0-9]", "").length() > 4) {
return false;
}
Matcher m = NICKNAME_PATTERN.matcher(nickname);
return m.matches();
}
public static boolean validatePassword(String password) {
if (StringUtils.isEmpty(password)) {
return false;
}
Matcher m = PASSWORD_PATTERN.matcher(password);
return m.matches();
}
public static boolean validateCode(String code) {
if (StringUtils.isEmpty(code)) {
return false;
}
Matcher m = CODE_PATTERN.matcher(code);
return m.matches();
}
public static boolean validatePostcode(String postcode) {
if (StringUtils.isEmpty(postcode)) {
return false;
}
Matcher m = POSTCODE_PATTERN.matcher(postcode);
return m.matches();
}
public static boolean validateBankCardNumber(String bankCardNumber) {
if (StringUtils.isEmpty(bankCardNumber)) {
return false;
}
Matcher m = BANK_CARD_PATTERN.matcher(bankCardNumber);
return m.matches();
}
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("Cdn-Src-Ip");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (StringUtils.hasText(ip)) {
return StringUtils.tokenizeToStringArray(ip, ",")[0];
}
return "";
}
public static Timestamp getTimestamp() {
Timestamp d = new Timestamp(System.currentTimeMillis());
return d;
}
public static String getUUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid.toUpperCase();
}
public static String md5(String data) throws IOException {
return md5(data, 1);
}
public static String md5(String data, int time) throws IOException{
byte[] bytes = data == null ? new byte[0] : data.getBytes("UTF-8");
while (time-- > 1) {
bytes = DigestUtils.md5Digest(bytes);
}
return DigestUtils.md5DigestAsHex(bytes).toUpperCase();
}
public static <T> T normalizeBlankStringFields(T object) {
if (object == null) return null;
PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils();
Stream.of(utils.getPropertyDescriptors(object)).forEach(pd -> {
try {
Object value = utils.getNestedProperty(object, pd.getName());
if (value == null) return;
if (!StringUtils.hasText(value.toString())) {
utils.setNestedProperty(object, pd.getName(), null);
}
} catch (Throwable e) {
}
});
return object;
}
public static Integer getGenderByIdNumber(String idNumber) {
int gender = 0;
if (idNumber.length() == 15) {
gender = Integer.parseInt(String.valueOf(idNumber.charAt(14))) % 2 == 0 ? 2 : 1;
} else if (idNumber.length() == 18) {
gender = Integer.parseInt(String.valueOf(idNumber.charAt(16))) % 2 == 0 ? 2 : 1;
}
return gender;
}
public static String getBirthdayByIdNumber(String idNumber) {
String birthday = "";
if (idNumber.length() == 15) {
birthday = "19" + idNumber.substring(6, 8) + "-" + idNumber.substring(8, 10) + "-" + idNumber.substring(10, 12);
} else if (idNumber.length() == 18) {
birthday = idNumber.substring(6, 10) + "-" + idNumber.substring(10, 12) + "-" + idNumber.substring(12, 14);
}
return birthday;
}
public static Integer getAgeByIdNumber(String idNumber) {
String birthString = getBirthdayByIdNumber(idNumber);
if (StringUtils.isEmpty(birthString)) {
return 0;
}
return getAgeByBirthString(birthString);
}
public static Integer getAgeByIdNumber(String idNumber, boolean isNominalAge) {
String birthString = getBirthdayByIdNumber(idNumber);
if (StringUtils.isEmpty(birthString)) {
return 0;
}
return getAgeByBirthString(birthString, isNominalAge);
}
public static Integer getAgeByBirthDate(Date birthDate) {
return getAgeByBirthString(new SimpleDateFormat("yyyy-MM-dd").format(birthDate));
}
public static Integer getAgeByBirthString(String birthString) {
return getAgeByBirthString(birthString, "yyyy-MM-dd");
}
public static Integer getAgeByBirthString(String birthString, boolean isNominalAge) {
return getAgeByBirthString(birthString, "yyyy-MM-dd", isNominalAge);
}
public static Integer getAgeByBirthString(String birthString, String format) {
return getAgeByBirthString(birthString, "yyyy-MM-dd", false);
}
public static Integer getAgeByBirthString(String birthString, String format, boolean isNominalAge) {
int age = 0;
if (StringUtils.isEmpty(birthString)) {
return age;
}
if (StringUtils.isEmpty(format)) {
format = "yyyy-MM-dd";
}
try {
Calendar birthday = Calendar.getInstance();
Calendar today = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(format);
birthday.setTime(sdf.parse(birthString));
age = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
if (!isNominalAge) {
if (today.get(Calendar.MONTH) < birthday.get(Calendar.MONTH) ||
(today.get(Calendar.MONTH) == birthday.get(Calendar.MONTH) &&
today.get(Calendar.DAY_OF_MONTH) < birthday.get(Calendar.DAY_OF_MONTH))) {
age = age - 1;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return age;
}
public static String maskMobile(String mobile) {
if (validateMobile(mobile)) {
return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
return mobile;
}
public static String maskMobile(String mobile, String transCode) {
if (validateMobile(mobile)) {
transCode = StringUtils.isEmpty(transCode) ? "****" : transCode;
return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", String.format("$1%s$2", transCode));
}
return mobile;
}
public static String maskEmail(String email) {
if (validateEmail(email)) {
String userName = email.substring(0, email.indexOf("@"));
int len = userName.length();
if (len >= 5) {
int total = len - 3;
int half = total / 2;
int start = half;
int end = len - half;
if (total % 2 != 0) {
end = end - 1;
}
StringBuilder sb = new StringBuilder(email);
for (int i = start; i < end; i++) {
sb.setCharAt(i, '*');
}
return sb.toString();
}
}
return email;
}
public static String maskTradeAccount(String account) {
return account.replaceAll("(\\d{7})\\d*(\\d{4})", "$1****$2");
}
public static boolean validateDate(String date) {
boolean convertSuccess = true;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
try {
format.setLenient(false);
format.parse(date);
} catch (ParseException e) {
convertSuccess = false;
}
return convertSuccess;
}
private static final Lock lock = new ReentrantLock();
public static long getUniqueLong() {
long l;
lock.lock();
try {
l = System.currentTimeMillis();
} finally {
lock.unlock();
}
return l;
}
public static String getUrlParams(String URL, String key) {
Map<String, String> mapRequest = new HashMap<String, String>();
String[] arrSplit = null;
String strUrlParam = null;
java.net.URL aURL = null;
try {
aURL = new URL(URL);
strUrlParam = aURL.getQuery();
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (strUrlParam == null) {
return "";
}
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
if (arrSplitEqual.length > 1) {
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (!StringUtils.isEmpty(arrSplitEqual[0])) {
mapRequest.put(arrSplitEqual[0], "");
}
}
}
if (mapRequest.containsKey(key)) {
try {
return URLDecoder.decode(mapRequest.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
return "";
}
public static String genRandomNum(int pwd_len) {
final int maxNum = 36;
int i;
int count = 0;
char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
StringBuffer pwd = new StringBuffer("");
Random r = new Random();
while (count < pwd_len) {
i = Math.abs(r.nextInt(maxNum));
if (i >= 0 && i < str.length) {
pwd.append(str[i]);
count++;
}
}
return pwd.toString();
}
}
邮件发送工具类
邮件工具类是通过JavaEmail实现,企业级项目一般都会专门的服务去发送邮件,但如果自己的小Demo,用工具类发送Email也未尝不可。示例Demo如下,有兴趣的可以fork代码自己研究一下,代码有详情的注释。
public class EmailUtilTest {
@Before
public void before() throws GeneralSecurityException {
EmailUtil.config(EmailUtil.SMTP_QQ(false), "xxx@qq.com", "xxxxxx");
}
@Test
public void testSendText() throws MessagingException {
System.out.println("test");
}
}
|