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();
}
}