java身份证校验
package com.zhdj.utilts;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IdCardVerification {
/**身份证有效*/
public static final String VALIDITY = "该身份证有效!";
/**位数不足*/
public static final String LACKDIGITS = "身份证号码长度应该为15位或18位。";
/**最后一位应为数字*/
public static final String LASTOFNUMBER = "身份证15位号码都应为数字 ; 18位号码除最后一位外,都应为数字。";
/**出生日期无效*/
public static final String INVALIDBIRTH = "身份证出生日期无效。";
/**生日不在有效范围*/
public static final String INVALIDSCOPE = "身份证生日不在有效范围。";
/**月份无效*/
public static final String INVALIDMONTH = "身份证月份无效";
/**日期无效*/
public static final String INVALIDDAY = "身份证日期无效";
/**身份证地区编码错误*/
public static final String CODINGERROR = "身份证地区编码错误。";
/**身份证校验码无效*/
public static final String INVALIDCALIBRATION = "身份证校验码无效,不是合法的身份证号码";
/**
* 检验身份证号码是否符合规范
* @param IDStr 身份证号码
* @return 错误信息或成功信息
*/
public static RespUtil IDCardValidate(String IDStr) throws ParseException {
String tipInfo = VALIDITY;// 记录错误信息
String Ai = "";
// 判断号码的长度 15位或18位
if (IDStr.length() != 15 && IDStr.length() != 18) {
tipInfo = LACKDIGITS;
return RespUtil.error(tipInfo);
}
// 18位身份证前17位位数字,如果是15位的身份证则所有号码都为数字
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) {
tipInfo = LASTOFNUMBER;
return RespUtil.error(tipInfo);
}
// 判断出生年月是否有效
String strYear = Ai.substring(6, 10);// 年份
String strMonth = Ai.substring(10, 12);// 月份
String strDay = Ai.substring(12, 14);// 日期
if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
tipInfo = INVALIDBIRTH;
return RespUtil.error(tipInfo);
}
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
try {
if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
|| (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
tipInfo = INVALIDSCOPE;
return RespUtil.error(tipInfo);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
tipInfo = INVALIDMONTH;
return RespUtil.error(tipInfo);
}
if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
tipInfo = INVALIDDAY;
return RespUtil.error(tipInfo);
}
// 判断地区码是否有效
Hashtable<String, String> areacode = GetAreaCode();
// 如果身份证前两位的地区码不在Hashtable,则地区码有误
if (areacode.get(Ai.substring(0, 2)) == null) {
tipInfo = CODINGERROR;
return RespUtil.error(tipInfo);
}
if (isVarifyCode(Ai, IDStr) == false) {
tipInfo = INVALIDCALIBRATION;
return RespUtil.errorIdFli(tipInfo);
}
return RespUtil.success(tipInfo);
}
/*
* 判断第18位校验码是否正确 第18位校验码的计算方式:
* 1. 对前17位数字本体码加权求和 公式为:S = Sum(Ai * Wi), i =
* 0, ... , 16 其中Ai表示第i个位置上的身份证号码数字值,Wi表示第i位置上的加权因子,其各位对应的值依次为: 7 9 10 5 8 4
* 2 1 6 3 7 9 10 5 8 4 2
* 2. 用11对计算结果取模 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
*/
private static boolean isVarifyCode(String Ai, String IDStr) {
String[] VarifyCode = { "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" };
int sum = 0;
for (int i = 0; i < 17; i++) {
sum = sum + Integer.parseInt(String.valueOf(Ai.charAt(i))) * Integer.parseInt(Wi[i]);
}
int modValue = sum % 11;
String strVerifyCode = VarifyCode[modValue];
Ai = Ai + strVerifyCode;
if (IDStr.length() == 18) {
if (Ai.equals(IDStr) == false) {
return false;
}
}
return true;
}
/**
* 将所有地址编码保存在一个Hashtable中
* @return Hashtable 对象
*/
private static Hashtable<String, String> GetAreaCode() {
Hashtable<String, String> hashtable = new Hashtable<String, String>();
hashtable.put("11", "北京");
hashtable.put("12", "天津");
hashtable.put("13", "河北");
hashtable.put("14", "山西");
hashtable.put("15", "内蒙古");
hashtable.put("21", "辽宁");
hashtable.put("22", "吉林");
hashtable.put("23", "黑龙江");
hashtable.put("31", "上海");
hashtable.put("32", "江苏");
hashtable.put("33", "浙江");
hashtable.put("34", "安徽");
hashtable.put("35", "福建");
hashtable.put("36", "江西");
hashtable.put("37", "山东");
hashtable.put("41", "河南");
hashtable.put("42", "湖北");
hashtable.put("43", "湖南");
hashtable.put("44", "广东");
hashtable.put("45", "广西");
hashtable.put("46", "海南");
hashtable.put("50", "重庆");
hashtable.put("51", "四川");
hashtable.put("52", "贵州");
hashtable.put("53", "云南");
hashtable.put("54", "西藏");
hashtable.put("61", "陕西");
hashtable.put("62", "甘肃");
hashtable.put("63", "青海");
hashtable.put("64", "宁夏");
hashtable.put("65", "新疆");
hashtable.put("71", "台湾");
hashtable.put("81", "香港");
hashtable.put("82", "澳门");
hashtable.put("91", "国外");
return hashtable;
}
/**
* 判断字符串是否为数字,0-9重复0次或者多次
* @param strnum
* @return true, 符合; false, 不符合。
*/
private static boolean isNumeric(String strnum) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(strnum);
if (isNum.matches()) {
return true;
} else {
return false;
}
}
/**
* 功能:判断字符串出生日期是否符合正则表达式:包括年月日,闰年、平年和每月31天、30天和闰月的28天或者29天
* @param
* @return true, 符合; false, 不符合。
*/
public static boolean isDate(String strDate) {
Pattern pattern = Pattern.compile(
"^((\\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]))))))?$");
Matcher m = pattern.matcher(strDate);
if (m.matches()) {
return true;
} else {
return false;
}
}
}
二维码绘制工具类
package com.zhdj.utilts;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.zhdj.pojo.LogoConfig;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
public class QuickMarkUtil {
//生成二维码时 的编码表
private static final String encode = "utf-8";
//二维码的图片格式
private static final String formatImg = "JPG";
//二维码的宽与高
private static final int quickMarkSize = 300;
/**
* 生成二维码
* @param content 二维码内容
* @param rgbColor 二维码颜色
* @throws Exception 主要是IO异常、溢出异常
*/
public static BufferedImage buildQuickMarkImage(String content, Integer rgbColor) throws Exception {
//定义集合,存放与二维码有关联的部分数据参数
HashMap<EncodeHintType, Object> hintsMap = new HashMap<>();
hintsMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hintsMap.put(EncodeHintType.CHARACTER_SET, encode);
hintsMap.put(EncodeHintType.MARGIN, 1);
//使用Google的二维码工具类来生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, quickMarkSize, quickMarkSize, hintsMap);
//把二维码画到图片缓冲区中,理解成画板
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//定义二维码颜色
if (rgbColor == null) {
rgbColor = 0x00000;
}
//开始画二维码矩阵
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? rgbColor : 0xFFFFFFFF);
}
}
// CreatrQrCode creatrQrCode = new CreatrQrCode(); //LogoConfig中设置Logo的属性
// addLogo_QRCode(qrcFile, creatrQrCode, creatrQrCode);
return bufferedImage;
}
public static BufferedImage buildQuickMarkImageFile(File content, Integer rgbColor) throws Exception {
//定义集合,存放与二维码有关联的部分数据参数
HashMap<EncodeHintType, Object> hintsMap = new HashMap<>();
hintsMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hintsMap.put(EncodeHintType.CHARACTER_SET, encode);
hintsMap.put(EncodeHintType.MARGIN, 1);
//使用Google的二维码工具类来生成二维码
// BitMatrix bitMatrix =new MultiFormatWriter().
BitMatrix bitMatrix = new MultiFormatWriter().encode(String.valueOf(content), BarcodeFormat.QR_CODE, quickMarkSize, quickMarkSize, hintsMap);
//把二维码画到图片缓冲区中,理解成画板
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//定义二维码颜色
if (rgbColor == null) {
rgbColor = 0x00000;
}
//开始画二维码矩阵
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? rgbColor : 0xFFFFFFFF);
}
}
// CreatrQrCode creatrQrCode = new CreatrQrCode(); //LogoConfig中设置Logo的属性
// addLogo_QRCode(qrcFile, creatrQrCode, creatrQrCode);
return bufferedImage;
}
public static void addLogo_QRCode(File qrPic, File logoPic,String name){
LogoConfig logoConfig =new LogoConfig();
try
{
if (!qrPic.isFile() || !logoPic.isFile())
{
System.out.print("file not find !");
System.exit(0);
}
/**
* 读取二维码图片,并构建绘图对象
*/
BufferedImage image = ImageIO.read(qrPic);
Graphics2D g = image.createGraphics();
/**
* 读取Logo图片
*/
BufferedImage logo = ImageIO.read(logoPic);
int widthLogo = image.getWidth()/logoConfig.getLogoPart();
// int heightLogo = image.getHeight()/logoConfig.getLogoPart();
int heightLogo = image.getWidth()/logoConfig.getLogoPart(); //保持二维码是正方形的
// 计算图片放置位置
int x = (image.getWidth() - widthLogo) / 2;
int y = (image.getHeight() - heightLogo) / 2 ;
//开始绘制图片
g.drawImage(logo, x, y, widthLogo, heightLogo, null);
g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
g.setStroke(new BasicStroke(logoConfig.getBorder()));
g.setColor(logoConfig.getBorderColor());
g.drawRect(x, y, widthLogo, heightLogo);
g.dispose();
ImageIO.write(image, "jpg", new File("D:/javaee_uniapp/graduation/图片管理/healthy/"+name));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 生成灰色二维码
*/
public static BufferedImage buildGrayQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.GRAY);
}
/**
* 生成绿色二维码
*/
public static BufferedImage buildBlueQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.BLUE);
}
public static BufferedImage buildGreenQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.GREEN);
}
/**
* 生成黄色二维码
*/
public static BufferedImage buildYellowQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.YELLOW);
}
public static BufferedImage buildDarkYellowQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.DARKYELLOW);
}
/**
* 生成红色二维码
*/
public static BufferedImage buildRedQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.RED);
}
public static BufferedImage buildDarkRedQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.DARKRED);
}
/**
* 生成纯黑色二维码
*/
public static BufferedImage buildBlackQuickMarkImage(String context) throws Exception {
return buildQuickMarkImage(context,Color.BLACK);
}
/**
* 图片写到本地
* @param path 保存路径
* @param image 图片内容
* @throws IOException Io异常
*/
public static void writeToLocal(String path,BufferedImage image) throws IOException {
File file = new File(path);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
ImageIO.write(image, formatImg, new File(path));
}
/**
* RGB颜色值
*/
public static class Color{
// 0xFF999 灰码
// 0xFF8CC152 浅绿码
// 0x006400 深绿码
// 0xFFCC3333 浅红码
// 0x800 深红码
// 0xFFFFFF00 浅黄码
// 0xFFDC00 深黄码
//0x000 黑码
public static final Integer GRAY=0xFFA9A9A9;
public static final Integer BLUE=0xFF8CC152;
public static final Integer GREEN =0x006400;
public static final Integer YELLOW=0xFFFFFF00;
public static final Integer RED=0xFFCC3333;
private static final Integer DARKRED=0x8B0000;
private static final Integer DARKYELLOW=0xFFDC00;
private static final Integer BLACK =0x000;
}
}
邮箱发送工具类
package com.resume.utils;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.Properties;
public class EmailUtil {
/**
* 外网邮件发送
*
* @param to 收件人邮箱地址 收件人@xx.com
* @param code 传入的验证码
*/
public static RespUtil sendMail(String to, String code) {
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
String time=formatter.format(date);
String myEmail = "2766324817@qq.com";
// Session对象:
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.qq.com"); // 设置主机地址
// smtp.163.com
// smtp.qq.com
// smtp.sina.com
props.setProperty("mail.smtp.auth", "true");// 认证
// 2.产生一个用于邮件发送的Session对象
Session session = Session.getInstance(props);
// Message对象:
Message message = new MimeMessage(session);
// 设置发件人:
try {
// 4.设置消息的发送者
Address fromAddr = new InternetAddress(myEmail);
message.setFrom(fromAddr);
// 5.设置消息的接收者 nkpxcloxbtpxdjai
Address toAddr = new InternetAddress(to);
// TO 直接发送 CC抄送 BCC密送
message.setRecipient(MimeMessage.RecipientType.TO, toAddr);
// 6.设置邮件标题
message.setSubject("来自 " + myEmail + " 的安全验证码");
// 7.设置正文
message.setContent("<h3> \n" +
"\t<span style=\"font-size:16px;\">亲爱的用户:</span> \n" +
"</h3>\n" +
"<p>\n" +
"\t<span style=\"font-size:14px;\"> </span><span style=\"font-size:14px;\"> <span style=\"font-size:16px;\"> 您好!您正在进行邮箱验证,本次请求的验证码为:<span style=\"font-size:24px;color:#FFE500;\"> "+code+"</span>,本验证码5分钟内有效,请在5分钟内完成验证。(请勿泄露此验证码)如非本人操作,请忽略该邮件。(这是一封自动发送的邮件,请不要直接回复)</span></span>\n" +
"</p>\n" +
"<p style=\"text-align:right;\">\n" +
"\t<span style=\"background-color:#FFFFFF;font-size:16px;color:#000000;\"><span style=\"color:#000000;font-size:16px;background-color:#FFFFFF;\"><span class=\"token string\" style=\"font-family:"font-size:16px;color:#000000;line-height:normal !important;background-color:#FFFFFF;\">"+myEmail+"</span></span></span> \n" +
"</p>\n" +
"<p style=\"text-align:right;\">\n" +
"\t<span style=\"background-color:#FFFFFF;font-size:14px;\"><span style=\"color:#FF9900;font-size:18px;\"><span class=\"token string\" style=\"font-family:"font-size:16px;color:#000000;line-height:normal !important;\"><span style=\"font-size:16px;color:#000000;background-color:#FFFFFF;\">"+time+"</span><span style=\"font-size:18px;color:#000000;background-color:#FFFFFF;\"></span></span></span></span> \n" +
"</p>", "text/html;charset=UTF-8");
// 8.准备发送,得到火箭
Transport transport = session.getTransport("smtp");
// 9.设置火箭的发射目标(第三个参数就是你的邮箱授权码)
//transport.connect("smtp.163.com", "发送者@163.com", "abcdefghabcdefgh");
transport.connect("smtp.qq.com", myEmail, "nwxcridhzioidddb");
// 10.发送
transport.sendMessage(message, message.getAllRecipients());
// Transport对象:
// Transport.send(message);
return RespUtil.reminder(200L,"邮件发送成功!!");
} catch (Exception e) {
e.printStackTrace();
return RespUtil.reminder(501L,"邮件发送失败!!");
}
}
public static String generateRandomCode(int length) {
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
while (sb.length() < length) {
// 0 ~ s.length()-1
int index = (new java.util.Random()).nextInt(s.length());
// 处理重复字符:每个新的随机字符在 sb 中使用indexOf()查找下标值,-1为没找到,即不重复
Character ch = s.charAt(index);
if (sb.indexOf(ch.toString()) < 0) {
sb.append(ch);
}
}
return sb.toString();
}
}
token生成工具类
package com.resume.utils;
import com.auth0.jwt.JWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/*
* @author qiaoyn
* @date 2019/06/14
* @version 1.0
*/
public class TokenUtil {
public static String getTokenUserId() {
String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
String userId = JWT.decode(token).getAudience().get(0);
return userId;
}
/**
* 获取request
*
* @return
*/
public static HttpServletRequest getRequest() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
return requestAttributes == null ? null : requestAttributes.getRequest();
}
}
前端响应工具类
package com.zhdj.utilts;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 公共返回对象
*
* @author wj
* @since 1.0.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RespUtil {
private long code;
private String message;
private Object obj;
public RespUtil(long code, String message) {
this.code=code;
this.message=message;
}
/**
* 返回成功的信息
* @param message
* @return
*/
public static RespUtil success(String message){
return new RespUtil(200,message,null);
}
/**
* 返回成功信息且带数据
* @param message
* @param obj
* @return
*/
public static RespUtil success(String message, Object obj){
return new RespUtil(200,message,obj);
}
public static RespUtil success( Object obj){
return new RespUtil(200,"查询成功!!!",obj);
}
/**
* 返回失败信息
* @param message
* @return
*/
public static RespUtil error(String message){
return new RespUtil(500,message,null);
}
public static RespUtil errorIdFli(String message){
return new RespUtil(5002,message,null);
}
/**
* 返回失败信息并带数据
* @param message
* @param obj
* @return
*/
public static RespUtil error(String message, Object obj){
return new RespUtil(500,message,obj);
}
public static RespUtil error(){
return new RespUtil(500,"查询失败!!!");
}
public static RespUtil errorPhone(){
return new RespUtil(5001,"该手机号码不存在!!!");
}
public static RespUtil errorTime(String message, Object obj){
return new RespUtil(304,message,obj);
}
public static RespUtil errorTime(String message){
return new RespUtil(304,message,null);
}
}
邮箱校验工具类
package com.resume.utils;
/**
* @ClassName EmailUtils
* 发送邮件工具
* @Author
* @Date 2020-04-16
**/
public class EmailAddressUtils {
/**
* 判断该邮件地址是否合法
*
* @return
*/
public static void isEmailAddress(String email) {
int count = 0; // 计算@的位置
int countd = 0; // 计算.的位置
for (int i = 0; i < email.length(); i++) {
char a = email.charAt(i); // 提取邮箱的所有字符
if (a == '.') {
countd = i + 1;
}
if (a == '@') {
count = i + 1;
}
}
if (count == 0) {
System.out.println("请注意你的邮箱格式:@符号缺失");
}
if ((count + 1) == countd) {
System.out.println("请注意你的邮箱格式:@与 . 之间没有名字");
}
String behind = email.substring(countd, (email.length())); // 提取.到邮箱尽头的内容
if (behind.equals("")) {
System.out.println("请注意你的邮箱格式:.后面没有地址");
}
String realm = email.substring(0, count-1); // 提取@前面的内容
System.out.println("你的邮箱用户名为:"+realm);
}
}
手机号码校验工具类
package com.zhdj.utilts;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class RegexUtils {
public static boolean isPhoneLegal(String str)throws PatternSyntaxException {
return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
}
/**
* 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
* 此方法中前三位格式有:
* 13+任意数
* 15+除4的任意数
* 18+任意数
* 17+除9的任意数
* 147
*/
public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
/**
* 香港手机号码8位数,5|6|8|9开头+7位任意数
*/
public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException {
String regExp = "^(5|6|8|9)\\d{7}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}
}
请求加密工具类
package com.zhdj.utilts;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class GetRequestJsonUtils {
public static JSONObject getRequestJsonObject(HttpServletRequest request) throws Exception {
String json = getRequestJsonString(request);
return JSONObject.parseObject(json);
}
public static JSONArray getRequestJsonArray(HttpServletRequest request) throws Exception {
String json = getRequestJsonString(request);
return JSONObject.parseArray(json);
}
/***
* 获取 request 中 json 字符串的内容
*
* @param request
* @return : <code>byte[]</code>
* @throws IOException
*/
public static String getRequestJsonString(HttpServletRequest request)
throws Exception {
String submitMehtod = request.getMethod();
// GET
if (submitMehtod.equals("GET")) {
String queryString=request.getQueryString();
if(queryString==null){
throw new Exception("请求没带参数");
}
return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
// POST
} else {
return getRequestPostStr(request);
}
}
/**
* 描述:获取 post 请求的 byte[] 数组
* <pre>
* 举例:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
/**
* 描述:获取 post 请求内容
* <pre>
* 举例:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static String getRequestPostStr(HttpServletRequest request)
throws Exception {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
}