效果图
后端Java代码
package com.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 验证码
*
* @author Adminsttrator
*
*/
public final class CodeNumber {
/**
* 以字符串形式返回生成的验证码,同时输出一个图片
*
* @param width 图片的宽度
* @param height 图片的高度
* @param imgType 图片的类型
* @param output 图片的输出流(图片将输出到这个流中)
* @return 返回所生成的验证码(字符串)
*/
public static String create(final int width, final int height, final String imgType, OutputStream output) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.getColor("F8F8F8"));
graphic.fillRect(0, 0, width, height);
Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
Color.CYAN };
// 在 "画板"上生成干扰线条 ( 30 是线条个数)
for (int i = 0; i < 30; i++) {
graphic.setColor(colors[random.nextInt(colors.length)]);
final int x = random.nextInt(width);
final int y = random.nextInt(height);
final int w = random.nextInt(20);
final int h = random.nextInt(20);
final int signA = random.nextBoolean() ? 1 : -1;
final int signB = random.nextBoolean() ? 1 : -1;
graphic.drawLine(x, y, x + w * signA, y + h * signB);
}
// 在 "画板"上绘制字母
graphic.setFont(new Font("cursive", Font.PLAIN, 28));
for (int i = 0; i < 4; i++) {// 4个验证码
final int temp = random.nextInt(26) + 97;
String s = String.valueOf((char) temp);
sb.append(s);
graphic.setColor(colors[random.nextInt(colors.length)]);
graphic.drawString(s, i * (width / 6)+10, height - (height / 3));// 间隔
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
使用(请求)
这里是SSH中使用response响应给页面(使用了response就不需要返回值)
/**
*验证码
* @return
*/
public String getCode(){
HttpServletResponse response = getResponse();
HttpSession session = getSession();
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
ResultHolder result1 = new ResultHolder();
try {
String code = CodeNumber.create(80, 36, "jpg", response.getOutputStream());
result1.setData(code);
session.setAttribute("codeNumber", code.toLowerCase());// 大写转小写
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
前端html
<img id="codeImg" src="" class="code_img" onclick="getCode()">
JS
// 获取验证码
function getCode(){
$("#codeImg").attr("src","LoginAction!getCode?v="+Math.random());// 这里发送请求就可以
}
然后这个简单的验证码实现就完成了
实现说明
在后端判断登录错误失败多少次后,返回的次数值给前端JS中判断大于规定的就显示验证码
在后端生成验证码后存放到session中
次数大于规定后验证码为必填,后端也需要进行校验
校验时,判断次数大于规定的范围是否,且获取session中的code判断是否与输入一致
登录成功后判断次数值改为0