public class StringUtils {
/**
* isBlank(這裏用一句話描述這個方法的作用)
*/
public static boolean isBlank(String content) {
return (content == null || "".equals(content));
}
/**
* checkEmail,作用:郵箱格式驗證
* /
public static boolean checkEmail(String email) {
boolean flag = false;
try {
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
} catch (Exception e) {
flag = false;
}
return flag;
}
/**
* checkMobile,作用:手機號碼格式驗證
*/
public static boolean checkMobile(String phone) {
boolean flag = false;
try {
String check = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(phone);
flag = matcher.matches();
} catch (Exception e) {
flag = false;
}
return flag;
}
/**
* 身份證號碼驗證 1、號碼的結構 公民身份號碼是特徵組合碼,由十七位數字本體碼和一位校驗碼組成。排列順序從左至右依次爲:六位數字地址碼,
* 八位數字出生日期碼,三位數字順序碼和一位數字校驗碼。 2、地址碼(前六位數)
* 表示編碼對象常住戶口所在縣(市、旗、區)的行政區劃代碼,按GB/T2260的規定執行。 3、出生日期碼(第七位至十四位)
* 表示編碼對象出生的年、月、日,按GB/T7408的規定執行,年、月、日代碼之間不用分隔符。 4、順序碼(第十五位至十七位)
* 表示在同一地址碼所標識的區域範圍內,對同年、同月、同日出生的人編定的順序號, 順序碼的奇數分配給男性,偶數分配給女性。 5、校驗碼(第十八位數)
* (1)十七位數字本體碼加權求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ,先對前17位數字的權求和
* Ai:表示第i位置上的身份證號碼數字值 Wi:表示第i位置上的加權因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4
* 2 (2)計算模 Y = mod(S, 11) (3)通過模得到對應的校驗碼 Y: 0 1 2 3 4 5 6 7 8 9 10 校驗碼: 1 0
* X 9 8 7 6 5 4 3 2
*/
/**
* 校驗身份證
*
* @param idCard
* @return 校驗通過返回true,否則返回false
* @throws ParseException
* @throws NumberFormatException
*/
public static boolean isIDCard(String iDStr) throws Exception {
/*String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
return Pattern.matches(REGEX_ID_CARD, idCard);*/
boolean errorInfo = true;//
String[] valCodeArr = { "1", "0", "X", "9", "8", "7", "6", "5", "4",
"3", "2" };
String[] wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
"9", "10", "5", "8", "4", "2" };
String ai = "";
// ================ 號碼的長度 15位或18位(begin) ================
if (iDStr.length() != 15 && iDStr.length() != 18) {
errorInfo = false;
return errorInfo;
}
// =======================(end)========================
// ================ 數字 除最後以爲都爲數字 ================
if (iDStr.length() == 18) {
ai = iDStr.substring(0, 17);
} else if (iDStr.length() == 15) {
ai = iDStr.substring(0, 6) + "19" + iDStr.substring(6, 15);
}
if (isNumeric(ai) == false) {
log.info("身份證15位號碼都應爲數字 ; 18位號碼除最後一位外,都應爲數字。");
/*errorInfo = "身份證號含有非法字符";*/
errorInfo = false;
return errorInfo;
}
// ============號碼的長度 15位或18位(end)========================
// ================ 出生年月是否有效 ================
String strYear = ai.substring(6, 10);// 年份
String strMonth = ai.substring(10, 12);// 月份
String strDay = ai.substring(12, 14);// 月份
if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
/*errorInfo = "身份證生日無效。";*/
errorInfo = false;
return errorInfo;
}
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
|| (gc.getTime().getTime() - s.parse(
strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
log.info("身份證生日不在有效範圍");
/*errorInfo = "身份證生日無效";*/
errorInfo = false;
return errorInfo;
}
if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
/*errorInfo = "身份證月份無效";*/
errorInfo = false;
return errorInfo;
}
if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
/*errorInfo = "身份證日期無效";*/
errorInfo = false;
return errorInfo;
}
// =====================(end)=====================
// ================ 地區碼時候有效 ================
Hashtable h = getAreaCode();
if (h.get(ai.substring(0, 2)) == null) {
/*errorInfo = "身份證地區編碼錯誤。";*/
errorInfo = false;
return errorInfo;
}
// ==============================================
// ================ 判斷最後一位的值 ================
int totalmulAiWi = 0;
for (int i = 0; i < 17; i++) {
totalmulAiWi = totalmulAiWi
+ Integer.parseInt(String.valueOf(ai.charAt(i)))
* Integer.parseInt(wi[i]);
}
int modValue = totalmulAiWi % 11;
String strVerifyCode = valCodeArr[modValue];
ai = ai + strVerifyCode;
if (iDStr.length() == 18) {
if (ai.equals(iDStr) == false) {
log.debug("輸入的身份證號:" + iDStr + ",正確的身份證號:" + ai);
/*errorInfo = "身份證號末位應該爲"
+ ai.substring(ai.length() - 1, ai.length());*/
errorInfo = false;
if (iDStr.charAt(17) == 'x') {
/*errorInfo = "身份證號末位應爲大寫X";*/
errorInfo = false;
}
return errorInfo;
}
} else {
errorInfo = true;
return errorInfo;
}
// =====================(end)=====================
return errorInfo;
}
/**
* 匹配中國郵政編碼
*
* @param postcode 郵政編碼
* @return 驗證成功返回true,驗證失敗返回false
*/
public static boolean isPostCode(String postCode) {
String reg = "\\d{6}";
return Pattern.matches(reg, postCode);
}
/**
* 生成一個32位的UUID 生成id另外一種方式
* @return
*/
public static String randomUUID() {
return UUID.randomUUID().toString().replace("-","");
}
/**
* double 取消科學計數法顯示 1.2345678945612E11
* @param d1
* @param d2
* @return
*/
public static String doubleFormat(double d1){
NumberFormat nf = NumberFormat.getInstance();
//設置保留多少位小數
nf.setMaximumFractionDigits(2);
// 取消科學計數法
nf.setGroupingUsed(false);
return nf.format(d1);
}
/**
* double 相加
* @param d1
* @param d2
* @return
*/
public static double add(double d1,double d2){
BigDecimal bd1 = new BigDecimal(Double.toString(d1));
BigDecimal bd2 = new BigDecimal(Double.toString(d2));
return bd1.add(bd2).doubleValue();
}
/**
* double 相減
* @param d1
* @param d2
* @return
*/
public static double sub(double d1,double d2){
BigDecimal bd1 = new BigDecimal(Double.toString(d1));
BigDecimal bd2 = new BigDecimal(Double.toString(d2));
return bd1.subtract(bd2).doubleValue();
}
/**
* double 乘法
* @param d1
* @param d2
* @return
*/
public static double mul(double d1,double d2){
BigDecimal bd1 = new BigDecimal(Double.toString(d1));
BigDecimal bd2 = new BigDecimal(Double.toString(d2));
return bd1.multiply(bd2).doubleValue();
}
/**
* double 除法
* @param d1
* @param d2
* @param scale 四捨五入 小數點位數
* @return
*/
public static double div(double d1,double d2,int scale){
// 當然在此之前,你要判斷分母是否爲0,
// 爲0你可以根據實際需求做相應的處理
BigDecimal bd1 = new BigDecimal(Double.toString(d1));
BigDecimal bd2 = new BigDecimal(Double.toString(d2));
return bd1.divide(bd2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 指定位數隨機數 生成id
* @return
*/
public static String getRandomNum(int num){
String numStr = "";
for(int i = 0; i < num; i++){
numStr += (int)(10*(Math.random()));
}
return numStr;
}
/**
* 根據傳入日期獲取YYYY-MM-DD類型日期
* @return
*/
public static String getDate(Date date){
String dateStr="";
//yyyyMMddHHmmss
//yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
dateStr=sdf.format(date);
return dateStr;
}
/**
* 獲得兩個日期之間相差的天數
* @param time1:開始時間
* @param time2:結束時間
* @return:兩個日期之間相差的天數
*/
public static int getTimeDifferenceDays(String startTime, String endTime) throws Exception{
long days = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date1 = ft.parse(startTime);
Date date2 = ft.parse(endTime);
days = date2.getTime() - date1.getTime();
days = days / 1000 / 60 / 60 / 24;
} catch (Exception e) {
throw e;
}
int day = new Long(days).intValue();
return day;
}
/**
* 獲取兩日期相差幾月
* @param date1 <String>
* @param date2 <String>
* @return int
* @throws ParseException
*/
public static int getMonthSpace(String date1, String date2)
throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar bef = Calendar.getInstance();
Calendar aft = Calendar.getInstance();
bef.setTime(sdf.parse(date1));
aft.setTime(sdf.parse(date2));
int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
return Math.abs(month + result);
}
/**
* 把一個字符串中大寫字母變小寫
* @param str
* @return
*/
public static String exChange(String str){
str.toUpperCase();
char[] ch = str.toCharArray();
StringBuffer sb = new StringBuffer();
int a = 'A'-'a'; //獲得大小寫之間差值
for(int i = 0; i < ch.length; i++){
if('a' <= ch[i] && ch[i] <= 'z'){
ch[i] = (char)(ch[i]+a);
}
sb.append(ch[i]);
}
return sb.toString();
}
/***
* 獲取客戶端IP地址
* @return
*/
public static String getClintIP (HttpServletRequest request) {
if (StringUtils.isBlank(request)) {
MessageContext mc = MessageContext.getCurrentMessageContext();
if (StringUtils.isBlank(mc)){
return "此處不應打印IP(作爲方法沒傳request)";
}
HttpServletRequest requestWebservice = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
String ip = requestWebservice.getHeader("X-Forwarded-For");
if(!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
//多次反向代理後會有多個ip值,第一個ip纔是真實ip
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = requestWebservice.getHeader("X-Real-IP");
if(!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
return requestWebservice.getRemoteAddr();
}else {
String ip = request.getHeader("X-Forwarded-For");
if(!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
//多次反向代理後會有多個ip值,第一個ip纔是真實ip
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if(!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
}
return request.getRemoteAddr();
}
}