java 验证码博客园_java验证码实现

@RequestMapping(value={"image"})

public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

//controller中生成验证码的方法

/*

* bufferedImage(参数一,参数二,参数三)

* 参数一:表示验证码的长度 68

* 参数二:表示验证码的宽度 25

*/

BufferedImage bufferedImage = new BufferedImage(68, 25, BufferedImage.TYPE_INT_RGB);

Graphics graphics = bufferedImage.getGraphics();

/*

* Color(参数一,参数二,参数三)

* 三个参数表示的是三基色。可以自己调整

*/

Color color = new Color(225, 230, 246);

graphics.setColor(color);

//设置字体样式和大小

graphics.setFont(new Font("Times New Roman", Font.PLAIN, 20));

graphics.fillRect(0, 0, 68, 25);

char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

Random random = new Random();

int length = chars.length;

StringBuffer buffer = new StringBuffer();

int index;

for (int i = 0; i < 4; i++) {

index = random.nextInt(length);

graphics.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));

graphics.drawString(chars[index] + "", (i * 15) + 3, 18);

buffer.append(chars[index]);

}

request.getSession().setAttribute("code", buffer.toString());

ImageIO.write(bufferedImage, "JPG", response.getOutputStream());

}

/**

* controller中验证码验证方法

*/

@RequestMapping(value={"checkCode"})

private String checkCode(CwUser user,HttpSession session, String code,RedirectAttributes redirectAttributes) {

String codeSession = (String) session.getAttribute("code");

System.out.println(user+"------"+codeSession);

if (code.equalsIgnoreCase(codeSession)) {

if (cwUserService.login(user) != null) {

addMessage(redirectAttributes, "登录成功");

System.out.println("登录成功");

return "redirect:" + adminPath + "/aa/bb/loginList";

}else {

addMessage(redirectAttributes, "用户名或密码错误");

System.out.println("用户名或密码错误");

return "redirect:" + adminPath + "/aa/bb/";

}

}else {

addMessage(redirectAttributes, "验证码有误");

System.out.println("验证码有误");

return "redirect:" + adminPath + "/aa/bb/";

}

}

/**

* jsp页面代码

*/

账户:

密码:

验证码://放置一个img标签,src图片地址里写controller里生成验证码的方法路劲。onclick方法是点击验证码更换,也可以点击看不清来更换

输入验证码

看不清

/**

* 更换验证码方法

*/

function reload() {

var time = new Date().getTime();

document.getElementById("image").src = "${ctx}/aa/bb/image?id=" + time;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值