最近在做web项目中,总结了验证码的问题,经过一番挣扎,彻底解决!
截图留念:
大家都是程序员,没有那么多废话,直接上代码!
No.1: Cotroller中这么写:
package cn.legocloud.controller;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.legocloud.util.CaptchaUtil;
/**
* ClassName: UtilController
* @Description: 工具控制层
* @Author GhostBride Morgana
* @Date 日期:2017-10-10 时间:下午6:42:27
*/
@Controller
@RequestMapping(value = "/Util")
public class UtilController {
/**
* @Description: 获取验证码
* @param @param request
* @param @param response
* @param @param session
* @throws IOException
* @Author GhostBride Morgana
* @Date 日期:2017-10-10 时间:下午6:41:26
*/
@RequestMapping(value = "/Captcha", produces="text/html;charset=UTF-8;")
public void Captcha(HttpServletRequest request,
HttpServletResponse response, HttpSession session) throws IOException {
CaptchaUtil captchautil = new CaptchaUtil();
//验证码存在session中
session.setAttribute("code", captchautil.getCode());
//验证码图片发送到页面
OutputStream out = response.getOutputStream();
ImageIO.write(captchautil.getBuffImg(), "png", out);
out.close();
}
}
No.2:工具类这么写:
package cn.legocloud.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* ClassName: CaptchaUtil
* Description: 验证码工具类
* date: 2017-9-22 下午4:12:23
*
* @version V 1.0.0
* @since JDK 1.7
* @author DarrenMJ 西安乐高云智能科技有限公司
*/
public class CaptchaUtil {
private int width = 120; // 图片的宽度
private int height = 40; // 图片的高度
private int count = 4; // 验证码字符个数
private int line = 25; // 验证码干扰线数
private String code = null; // 验证码
private BufferedImage buffImg = null; // 验证码图片Buffer
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 Integer[] colorList = { 0x000000, 0xFF0000, 0x00FF00, 0x0000FF,
0xFF00FF, 0x00FFFF, 0x800000, 0x008000, 0x000080, 0x808000,
0x008080, 0xC0C0C0, 0x808080, 0x9999FF, 0x993366, 0x660066,
0xFF8080, 0x0066CC, 0x00CCFF, 0xCC99FF, 0x3366FF, 0x33CCCC,
0xFF6600 };
/**
* CaptchaUtil 构造方法
*/
public CaptchaUtil() {
this.createCode();
}
/**
* CaptchaUtil 构造方法
*
* @param width 图片宽
* @param height 图片高
*/
public CaptchaUtil(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
* CaptchaUtil 构造方法
*
* @param width 图片宽
* @param height 图片高
* @param count 字符个数
* @param line 干扰线条数
*/
public CaptchaUtil(int width, int height, int count, int line) {
this.width = width;
this.height = height;
this.count = count;
this.line = line;
this.createCode();
}
/**
* createCode:创建验证码
*
* @since JDK 1.7
* @author DarrenMJ 西安乐高云智能科技有限公司
*/
public void createCode() {
int x = 0;
int codeY = 0;
int red = 0, green = 0, blue = 0;
x = (width / count) - 1;// 每个字符的宽度
// 开始X座标
int startX = (width - x * count) / 2;
codeY = height - 12;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 生成随机数
Random random = new Random();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体
Font baseFont = new Font("Tempus Sans ITC", Font.ITALIC, 35);
g.setFont(baseFont);
//画边框
g.setColor(Color.DARK_GRAY);
g.drawRect(0,0,width-1,height-1);
// randomCode记录随机产生的验证码
StringBuffer randomCode = new StringBuffer();
// 随机产生codeCount个字符的验证码。
for (int i = 0; i < count; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(colorList[random.nextInt(colorList.length)]));
if (i == 0) {
g.drawString(strRand, startX, codeY);
} else {
g.drawString(strRand, (i * x + 4), codeY);
}
// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
// 干扰线
for (int i = 0; i < line; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width / 8);
int ye = ys + random.nextInt(height / 8);
red = random.nextInt(155);
green = random.nextInt(155);
blue = random.nextInt(155);
g.setColor(new Color(red, green, blue));
g.drawLine(xs, ys, xe, ye);
}
// 将四位数字的验证码保存到Session中。
code = randomCode.toString();
}
/**
* write:指定路径输出验证码图片
*
* @param path 指定路径
* @throws IOException
* @since JDK 1.7
* @author DarrenMJ 西安乐高云智能科技有限公司
*/
public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}
public void write(OutputStream os) throws IOException {
ImageIO.write(buffImg, "png", os);
os.close();
}
/**
* getBuffImg:获取验证码图片
*
* @return
* @since JDK 1.7
* @author DarrenMJ 西安乐高云智能科技有限公司
*/
public BufferedImage getBuffImg() {
return buffImg;
}
/**
* getCode:获取验证码内容
*
* @return
* @since JDK 1.7
* @author DarrenMJ 西安乐高云智能科技有限公司
*/
public String getCode() {
return code;
}
/**java项目使用方法***********************************************************************/
/* 在本地创建验证码
public static void main(String[] args) {
CaptchaUtil captcha = new CaptchaUtil();
try {
String path = "D:/" + new Date().getTime() + ".png";
System.out.println(captcha.getCode() + " -> " + path);
captcha.write(path);
} catch (IOException e) {
e.printStackTrace();
}
}
*/
/**web项目使用方法***********************************************************************/
/* 实例化验证码实体类和工具类
CaptchaUtil captchautil = new CaptchaUtil();
//验证码存在session中
session.setAttribute("code", captchautil.getCode());
//验证码图片发送到页面
OutputStream out = response.getOutputStream();
ImageIO.write(captchautil.getBuffImg(), "png", out);
out.close();
*/
/************************************************************************************/
}
No.3:最后是html或者jsp或者其他,你爱玩什么就玩什么,和我关系不大:
<div class="weui-cell__ft">
<img class="weui-vcode-img" src="Util/Captcha" οnclick="javascript:this.src='Util/Captcha? tm='+Math.random()">
</div>
然后,就好了!你点一下试试,至于你们的行不行,反正我的行了。
点击验证码之前:
点了之后:
最后叮咛一句,你先改变图片,到工具类里面去修改,字体,大小,颜色,边框,间距都可以调!
好了就写到这里吧,我累了!
@Author GhostBride Morgana
@woshifu DarrenMJ