1.double转为字符串并保留4位
public static String doubleToString(Double v){
BigDecimal bigValue = new BigDecimal(v);
return bigValue.setScale(4, BigDecimal.ROUND_HALF_UP).toPlainString();
}
2.判断字符串是否为空
public static boolean isEmpty(Object obj) {
if (obj instanceof String) {
String anotherString = (String)obj;
if(StringUtils.isEmpty(anotherString)){
return true;
}else if("null".equalsIgnoreCase(anotherString)){
return true;
}else{
return false;
}
}else if(obj==null){
return true;
}else{
return false;
}
}
3.是否是数字
public static boolean isNumeric(Object str) {
if (isEmpty(str)) {
return false;
}
String strNum = String.valueOf(str);
int sz = strNum.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(strNum.charAt(i)) == false) {
return false;
}
}
return true;
}
4.包含中文标点符号
public static boolean hasChinese(String str) {
if (str == null) {
return false;
}
char[] ch = str.toCharArray();
for (char c : ch) {
if (isChinese(c)) {
return true;
}
}
return false;
}
5.验证是否是手机号
public static boolean isMobilePhone(String value)
{
String regex = "^[1]([3-9])[0-9]{9}$";
return value.matches(regex);
}
6.大写字母
public static boolean isUpChar(String str)
{
String regex = "^[A-Z]+$";
return match(regex, str);
}
7.输入的是字母
public static boolean isLetter(String str)
{
String regex = "^[A-Za-z]+$";
return match(regex, str);
}
8.校验网址
public static boolean isUrl(String str)
{
String regex = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
return match(regex, str);
}
9.邮箱的有效性
public static boolean isEmail(String str)
{
//return str.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+") ;
String regex = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
return match(regex, str);
}
10.double
public static boolean isDouble(String str) {
Pattern pattern = Pattern.compile("^[-//+]?//d+(//.//d*)?|//.//d+$");
return pattern.matcher(str).matches();
}
11.雪花算法
/**
* SnowFlake算法产生的ID是一个64位的整型,结构如下(每一部分用“-”符号分隔):
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
* 1位标识部分,在java中由于long的最高位是符号位,正数是0,负数是1,一般生成的ID为正数,所以为0;
* 41位时间戳部分,这个是毫秒级的时间,一般实现上不会存储当前的时间戳,而是时间戳的差值(当前时间-固定的开始时间),这样可以使产生的ID从更小值开始;41位的时间戳可以使用69年,(1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69年;
* 10位节点部分,Twitter实现中使用前5位作为数据中心标识,后5位作为机器标识,可以部署1024个节点;
* 12位序列号部分,支持同一毫秒内同一个节点可以生成4096个ID;
* SnowFlake算法生成的ID大致上是按照时间递增的,用在分布式系统中时,需要注意数据中心标识和机器标识必须唯一,
* 这样就能保证每个节点生成的ID都是唯一的。或许我们不一定都需要像上面那样使用5位作为数据中心标识,5位作为机器标识,
* 可以根据我们业务的需要,灵活分配节点部分,如:若不需要数据中心,完全可以使用全部10位作为机器标识;若数据中心不多,也可以只使用3位作为数据中心,7位作为机器标识。
*/
public class SnowFlake {
/**
* 起始时间
*/
private static final String EPOCH = "2019-01-01";
/**
* 数据中心
*/
private static final int DATACENTERID =4;
/**
* 机器标识
*/
private static final int MACHINEID =5;
/**
* 起始的时间戳
*/
private final static long START_STMP = DateUtil.parseDate(EPOCH).getTime();
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心(0~31)
private long machineId; //机器标识(0~31)
private long sequence = 0L; //序列号,毫秒内序列(0~4095)
private long lastStmp = -1L;//上一次时间戳
private volatile static SnowFlake snowFlake = null;
private SnowFlake(long datacenterId, long machineId){
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
private SnowFlake(){
this(DATACENTERID,MACHINEID);
}
/**
* 取得单例实现
* @return
*/
public static SnowFlake getInstance() {
if (snowFlake ==null) {
synchronized (SnowFlake.class){
if(snowFlake==null)
snowFlake = new SnowFlake();
}
}
return snowFlake;
}
/**
* 产生下一个ID(该方法是线程安全的)
*
* @return
*/
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private static long getNewstmp() {
return System.currentTimeMillis();
}
/**
* @name 测试
*/
public static void main(String[] args) {
System.out.print(System.currentTimeMillis());
for (int i = 0; i < (1 << 4); i++) {
System.out.println(SnowFlake.getInstance().nextId());
}
}
}
12.分页结果集工具
public class PageResponse<T> implements Serializable {
private static final long serialVersionUID = 0L;
/**
* 页码,从1开始
*/
private int pageNum;
/**
* 页面大小
*/
private int pageSize;
/**
* 总数
*/
private long total;
/**
* 总页数
*/
private int pages;
/**
* 查询列表
*/
private List<T> result;
public PageResponse(int pageNum, int pageSize, long total, List<T> result) {
super();
this.pageNum = pageNum;
this.pageSize = pageSize;
this.total = total;
if (pageNum % pageSize == 0) {
this.pages = pageNum / pageSize;
} else {
this.pages = pageNum / pageSize + 1;
}
this.result = result;
}
public PageResponse(int pageNum, int pageSize, long total, int pages, List<T> result) {
super();
this.pageNum = pageNum;
this.pageSize = pageSize;
this.total = total;
this.pages = pages;
this.result = result;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
}
13.properties文件读取
public class GlobalConfigProperties {
private static final Logger logger = LoggerFactory.getLogger(GlobalConfigProperties.class);
public static final String SYSTEM_PROPERTIES = "/all.properties";
private static Map<String, Properties> propertieMap = new HashMap<String, Properties>();
private static Map<String, String> propertieFileMap = new HashMap<String, String>();
static {
Properties properties = init(SYSTEM_PROPERTIES);
Iterator<Object> it = properties.keySet().iterator();
while (it.hasNext()) {
String name = (String) it.next();
String file = properties.getProperty(name);
file = file.trim();
propertieFileMap.put(name, file);
Properties p = init("/" + file);
propertieMap.put(name, p);
}
}
private static Properties init(String propertyFile) {
Properties p = new Properties();
try {
logger.info("Start Loading property file:" + propertyFile);
p.load(GlobalConfigProperties.class.getResourceAsStream(propertyFile));
logger.info("Load property file successfully:" + propertyFile);
} catch (Exception e) {
logger.error("Could not load property file:" + propertyFile, e);
}
return p;
}
public static String getProperty(String cls, String name) {
Properties p = (Properties) propertieMap.get(cls);
if (p != null) {
return p.getProperty(name);
}
return null;
}
public static boolean getBooleanProperty(String cls, String name) {
String p = getProperty(cls, name);
return "true".equalsIgnoreCase(p)||"1".equals(p);
}
public static Integer getIntegerProperty(String cls, String name) {
String p = getProperty(cls, name);
if (p == null) {
return null;
}
return Integer.valueOf(p);
}
public static Long getLongProperty(String cls, String name) {
String p = getProperty(cls, name);
if (p == null) {
return null;
}
return Long.valueOf(p);
}
public static Double getDoubleProperty(String cls, String name) {
String p = getProperty(cls, name);
if (p == null) {
return null;
}
return Double.valueOf(p);
}
}
14.多线程工具
public class MultiThreadJobsUtil {
private static final Logger log = LoggerFactory.getLogger(MultiThreadJobsUtil.class);
private static ExecutorService executor = new ThreadPoolExecutor(10, 20, 30L, TimeUnit.MINUTES,
new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("XYM-线程-" + t.getId());
return t;
}
});
public static <V> List<V> doJob(final List<Callable<List<V>>> jobs) {
List<V> result = new ArrayList<V>();
try {
if (!executor.isShutdown()) {
List<Future<List<V>>> results = executor.invokeAll(jobs);
for (Future<List<V>> future : results)
result.addAll(future.get());
}
} catch (InterruptedException e) {
log.error("线程中断异常", e);
} catch (ExecutionException e) {
log.error("线程执行异常", e);
} catch (Exception e) {
log.error("其它错误异常", e);
}
return result;
}
public static void doJob(final Runnable r) {
try {
if (!executor.isShutdown()) {
executor.submit(r);
}
} catch (Exception e) {
log.error("其它错误异常", e);
}
}
public static void shutdown() throws InterruptedException {
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);
executor.shutdownNow();
}
@Override
protected void finalize() throws Throwable {
shutdown();
}
}
15.加密解密DesUtils
import javax.crypto.Cipher;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DesUtils {
/**
* 字符串默认键值
*/
private static String strDefaultKey = "national";
/**
* 加密工具
*/
private Cipher encryptCipher = null;
/**
* 解密工具
*/
private Cipher decryptCipher = null;
/**
* 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[]
* hexStr2ByteArr(String strIn) 互为可逆的转换过程
*
* @param arrB 需要转换的byte数组
* @return 转换后的字符串
* @throws Exception 本方法不处理任何异常,所有异常全部抛出
*/
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
return sb.toString();
}
/**
* 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB)
* 互为可逆的转换过程
*
* @param strIn 需要转换的字符串
* @return 转换后的byte数组
* @throws Exception 本方法不处理任何异常,所有异常全部抛出
* @author <a href="mailto:leo841001@163.com">LiGuoQing</a>
*/
public static byte[] hexStr2ByteArr(String strIn) throws Exception {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
/**
* 默认构造方法,使用默认密钥
*
* @throws Exception
*/
public DesUtils() throws Exception {
this(strDefaultKey);
}
/**
* 指定密钥构造方法
* 由指定的秘钥生成加密器和解密器
*
* @param strKey 指定的密钥
* @throws Exception
*/
public DesUtils(String strKey) throws Exception {
Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance("DES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance("DES");
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
/**
* 加密字节数组
*
* @param arrB 需加密的字节数组
* @return 加密后的字节数组
* @throws Exception
*/
public byte[] encrypt(byte[] arrB) throws Exception {
return encryptCipher.doFinal(arrB);
}
/**
* 加密字符串
*
* @param strIn 需加密的字符串
* @return 加密后的字符串
* @throws Exception
*/
public String encrypt(String strIn) throws Exception {
return byteArr2HexStr(encrypt(strIn.getBytes()));
}
/**
* 解密字节数组
*
* @param arrB 需解密的字节数组
* @return 解密后的字节数组
* @throws Exception
*/
public byte[] decrypt(byte[] arrB) throws Exception {
return decryptCipher.doFinal(arrB);
}
/**
* 解密字符串
*
* @param strIn 需解密的字符串
* @return 解密后的字符串
* @throws Exception
*/
public String decrypt(String strIn) throws Exception {
return new String(decrypt(hexStr2ByteArr(strIn)));
}
/**
* 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
*
* @param arrBTmp 构成该字符串的字节数组
* @return 生成的密钥
* @throws Exception
*/
private Key getKey(byte[] arrBTmp) throws Exception {
// 创建一个空的8位字节数组(默认值为0)
byte[] arrB = new byte[8];
// 将原始字节数组转换为8位
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
// 生成密钥
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}
/**
* 明文转密文
*
* @throws Exception
*/
public static String password(String str) {
DesUtils des;
try {
if (str == null || str.trim().equals("")) return "";
des = new DesUtils("mmid");
String password = des.encrypt(str);
return password;
} catch (Exception e) {
return str;
}//自定义密钥
}
public static String password(String str, String key) throws Exception {
DesUtils des = new DesUtils(key);
String password = des.encrypt(str);
return password;
}
/**
* 密文转明文
*
* @throws Exception
*/
public static String clear(String str) {
DesUtils des;
//自定义密钥
try {
des = new DesUtils("fgh");
String clear = des.decrypt(str);
return clear;
} catch (Exception e) {
return "";
}
}
public static String clear(String str, String key) {
// Decript de = new Decript();
// String mmid =(String) de.getData().getMap().get("mmid");
String mmid = "fgh";
key = mmid;
DesUtils des = null;
try {
des = new DesUtils(key);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String clear = null;
try {
clear = des.decrypt(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clear;
}
/**
* 购买产品时生成的产品密钥(主要作为广告查询工具密钥使用)
*
* @param userIdentifier-用户唯一编码(7位)
* @param key-0为官网购买,1为工具生成(1位)
* @param StaffIdentifier-员工编号(4位,默认8011,区分是在员工那里购买的)
* @param agencyIdentifier-代理编号(5位,默认10000,区分在代理那里购买的)
* @param discount-折扣(2位)
* @param buying-购买时间,换算成1,2,3天数
*/
public static String createSecretKey(String userIdentifier, int key, int softwareType, String StaffIdentifier, String agencyIdentifier, String discount, int buying) {
String secretKey = null;
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String nowtime = sdf.format(date);
secretKey = password(userIdentifier + key + softwareType + nowtime + StaffIdentifier + agencyIdentifier + discount + buying);
return secretKey;
}
public static String createSecretKey(String nickname,
Double preferentialPrice, String staffIdentifier, String type,
String date) {
StringBuffer secStr = new StringBuffer();
secStr.append(nickname).append(">")
.append(preferentialPrice.intValue()).append(">")
.append(staffIdentifier).append(">").append(type).append(">")
.append(date);
try {
DesUtils des = new DesUtils("driver");
// System.out.println(secStr);
String sec = des.encrypt(secStr.toString());
// System.out.println(sec);
return sec;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
16.将base64编码字符串转换为字节流
/**
* @Description: 将base64编码字符串转换为字节流
* @Author:
* @CreateTime:
* @param imgStr base64编码字符串
* @return
*/
public static byte[] base64ToByte(String imgStr) {
if (imgStr == null){
return null;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
return decoder.decodeBuffer(imgStr);
//需要输出到文件时
/*FileOutputStream out = new FileOutputStream(filePath+File.separator+fileSuffix);
out.write(buffer);
out.close();*/
} catch (Exception e) {
logger.error("base64转为流异常:"+e.getMessage());
return null;
}
}
17.根据图片地址转换为base64编码字符串
/**
* @Description: 根据图片地址转换为base64编码字符串
* @Author:
* @CreateTime:
* @return
*/
public static String getImageToBase64(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
18.图片验证码
目的:
1) 验证操作者是否是人
2) 防止表单重复提交
生成验证码的要点:
1) 使用java代码生成图片对象
BufferedImage
2) 使用Random生成随机字符串
3) 将图片对象用
ImageIO.write(图片对象, "jpeg|png", 响应字节输出流)
返回给客户端浏览器
验证验证码:
要点:
1) 将验证码文字存入session作用域
2) 表单提交时,对比session中的验证码和表单中的验证码
————————————————
版权声明:本文为CSDN博主「浔者」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38454165/article/details/83097420
工具类:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
public class ImageUtil {
// 图片的宽度。
private int width = 160;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 5;
// 验证码干扰线数
private int lineCount = 150;
// 验证码
private String code = null;
private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private BufferedImage bufferedImage;
private ImageUtil(int width, int height){
this.width = width;
this.height = height;
}
public ImageUtil(int width, int height, int codeCount, int lineCount){
this(width, height);
this.codeCount = codeCount;
this.lineCount = lineCount;
createCodeImage();
}
private void createCodeImage(){
//字符所在x坐标
int x = 0;
//字体高度
int fontHeight = 0;
//字符所在y坐标
int codeY = 0;
int red = 0;
int green = 0;
int blue = 0;
x = width / (codeCount + 2);
fontHeight = height - 2;
codeY = height - 4;
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics2D graphics2D = bufferedImage.createGraphics();
Random random = new Random();
graphics2D.setColor(Color.WHITE);
graphics2D.fillRect(0, 0, width,height);
Font font = new Font("Fixedays",Font.PLAIN,fontHeight);
graphics2D.setFont(font);
for (int i = 0; i < lineCount; i++) {
//x轴第一个点的位置
int x1 = random.nextInt(width);
//y轴第一个点的位置
int y1 = random.nextInt(height);
//x轴第二个点的位置
int x2 = x1 + random.nextInt(width >> 2);
//y轴第二个点的位置
int y2 = y1 + random.nextInt(height >> 2);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
graphics2D.setColor(new Color(red, green, blue));
graphics2D.drawLine(x1, y1, x2, y2);
}
StringBuffer randomCode = new StringBuffer(codeCount);
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
graphics2D.setColor(new Color(red, green, blue));
graphics2D.drawString(strRand, (i +1) * x, codeY);
randomCode.append(strRand);
}
code = randomCode.toString();
}
public void write(String path) throws IOException {
OutputStream outputStream = new FileOutputStream(path);
this.write(outputStream);
outputStream.flush();
outputStream.close();
}
public void write(OutputStream outputStream) throws IOException {
ImageIO.write(bufferedImage, "png", outputStream);
}
public BufferedImage getBufferedImage(){
return bufferedImage;
}
public String getCode(){
return code;
}
}
控制层:
@GetMapping(value = "/code")
public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
response.setContentType("image/jpeg");
//禁止图像缓存
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
HttpSession session = request.getSession();
ImageUtil imageUtil = new ImageUtil(130, 40, 5,30);
session.setAttribute("code", imageUtil.getCode());
imageUtil.write(response.getOutputStream());
}
@GetMapping(value = "/verCode")
@ResponseBody
public Result<String> verCode(@RequestParam("verCode") String verCode, HttpServletRequest request, HttpServletResponse response) throws Exception{
request.setCharacterEncoding("utf-8");
String code=(String) request.getSession().getAttribute("code"); //从session中获取真正的验证码
//String verCode= request.getParameter("verCode");
if(verCode.equals(code)){
return new ResultSupport(true);
}
return new ResultSupport(false,"验证不通过");
}
前端:
<img id="vimg" th:src="@{code}"/>
$("#vimg").on("click",function () {
var timestamp = (new Date()).valueOf();
$(this).attr("src","code?timestamp=" + timestamp);
});
19.获取周几
/**
* 得到日期对应的星期几
*
* @param Date
* @return
*/
public static String getWeek(String Date) {
Date d = fomatDate(Date);
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(d);
if ("Mon".equals(dateStr)) {
dateStr = "星期一";
} else if ("Tue".equals(dateStr)) {
dateStr = "星期二";
} else if ("Wed".equals(dateStr)) {
dateStr = "星期三";
} else if ("Thu".equals(dateStr)) {
dateStr = "星期四";
} else if ("Fri".equals(dateStr)) {
dateStr = "星期五";
} else if ("Sat".equals(dateStr)) {
dateStr = "星期六";
} else if ("Sun".equals(dateStr)) {
dateStr = "星期日";
}
return dateStr;
}
20.n天前后
public static Date getAddDayDate(Date dt, int days) {
if (dt == null)
dt = new Date(System.currentTimeMillis());
Calendar calendar = Calendar.getInstance(); // 得到日历
calendar.setTime(dt);// 把当前时间赋给日历
calendar.add(Calendar.DATE, days); // 设置为前n月
return calendar.getTime();
}