在开发的时候,很多时候尤其是登录或者重要性操作的时候都需要验证码,怎么动态的生成验证码和检查验证码的有效性呢?
代码实例:http://download.csdn.net/detail/writerpan/7317467
效果图:


生成验证码的servlet:
package com.wq.services.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 验证码图片产生类
* @author Administrator
*
*/
public class MakeIdentifyingCode {
public static final String IDENTIFYINGCODEKEY = "IDENTIFYINGCODEKEY";//放入session的key值
private String code ="0123456789";//需要的验证码数据,从中取出stringNum个字符,可以在这里定制你的验证码
private int width = 80;//图片的宽
private int height = 26;//图片的高
private int linesize = 40;//干扰线的数量
private int stringNum = 4;//随机产生的字符数
private Random random = new Random();
private Font getFont(){//获得字体的函数
return new Font("Fixedsys",Font.CENTER_BASELINE,18);
}
private Color getRandColor(int fc,int bc){//获得随机颜色的函数
if(fc>255){
fc = 255;
}
if(bc>255){
bc = 255;
}
int r = fc+random.nextInt(bc-fc-16);
int g = fc+random.nextInt(bc-fc-14);
int b = fc+random.nextInt(bc-fc-18);
return new Color(r,g,b);
}
/**
* 获得随机图片,并设置在调用的servlect里
*/
public void getRandImage(HttpServletRequest request,HttpServletResponse response){
HttpSession session = request.getSession();
//在内存里创建一个图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();//得到该图片的画笔对象
g.fillRect(0, 0, width, height);//给图片填充一个长方形,颜色为白色
g.setFont(getFont());
g.setColor(getRandColor(110, 133));//设置画笔的的字体和颜色
for(int i=0;i<linesize;i++){//绘制干扰线
drowLine(g);
}
String randomString = "";
for(int i =1;i<=stringNum;i++){//绘制字符
randomString = drowString(g, randomString, i);
}
session.removeAttribute(IDENTIFYINGCODEKEY);//移除原有的值
session.setAttribute(IDENTIFYINGCODEKEY, randomString);//放入新的值
System.out.println(randomString);
g.dispose();
try {
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}//将图片的内容输出到浏览器端
}
/**
* 根据用户输入的验证码检查是否正确
* @param request
* @param response
* @param userCode 用户输入的验证码
* @return 正确返回true,不正确返回false
*/
public boolean checkIdentifyingCode(HttpServletRequest request,HttpServletResponse response,String userCode){
HttpSession session = request.getSession();
return userCode.equals(session.getAttribute(IDENTIFYINGCODEKEY));
}
private String drowString (Graphics g,String randomString,int i){//绘制字符串
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(code.length())));
randomString += rand;
g.translate(random.nextInt(3),random.nextInt(3));
g.drawString(rand, 13*i, 16);
return randomString;
}
private void drowLine(Graphics g){//绘制干扰线
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(13);
int y1 = random.nextInt(15);
g.drawLine(x, y, x+x1, y+y1);
}
private String getRandomString(int num){//取得随机的字符串
return String.valueOf(code.charAt(num));
}
}
调用验证码的jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>校友网注册页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../css/bootstrap.css" type="text/css"></link>
<link rel="stylesheet" href="../../css/gerenzhongxin/regest.css" type="text/css"></link>
<script type="text/javascript" src="../../js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="../../js/bootstrap.js"></script>
<script type="text/javascript" src="../../js/gerenzhongxin/regest.js"></script>
</head>
<body>
<div class="container">
<div class="regest">
<form id="registerfrom">
<div class="inputDiv">
用户帐号:<input type="text" id="user" name="user" onblur="VaildateInput('user')"/><span class="tips" id="userspan">*</span>
</div>
<div class="inputDiv">
登录密码:<input type="password" id="password" name="password" onblur="VaildateInput('password')"/><span class="tips" id="passwordspan">*</span>
</div>
<div class="inputDiv">
重复密码:<input type="password" id="password1" name="password1" onblur="VaildateInput('password1')"/><span class="tips" id="password1span">*</span>
</div>
<div class="inputDiv">
绑定邮箱:<input type="text" id="email" name="email" onblur="VaildateInput('email')"/><span class="tips" id="emailspan">*</span>
</div>
<div class="inputDiv">
真实姓名:<input type="text" id="realname" name="realname" onblur="VaildateInput('realname')"/><span class="tips" id="realnamespan">*</span>
</div>
<div class="inputDiv">
<textarea>用户条约:</textarea>
</div>
<div class="inputDiv">
<input type="radio" name="jieshou" value="1"/>接受
<input type="radio" name="jieshou" value="0"/>不接受
</div>
<div class="inputDiv">
<input type="text" value="请输入验证码" id="codeInput" name="codeInput"/><img src="<%=path%>/servlet/IdentifyingCode" id="IdentifyingCode"/><a id="ChangeIdentifyingCode">看不清?换一张</a><span id="codeInputspan"></span>
</div>
</form>
<div class="inputDiv">
<button id="regestButton">注册</button> <button>返回</button>
</div>
</div>
</div>
</body>
</html>
检测验证码的js:
$(function(){
myClilck();//自定义的事件
});
function myClilck(){
$("#ChangeIdentifyingCode").click(function(){//点击换验证码图片
$("#IdentifyingCode").attr("src","http://localhost:8080/xiaoyou/servlet/IdentifyingCode?"+new Date());
$("#codeInput").val("请输入验证码");
$("#codeInputspan").html("");
});
//验证框获得焦点的时候
$("#codeInput").focus(function(){
if($("#codeInput").val()=="请输入验证码"){
$(this).val("");
}
});
//验证框失去焦点的时候
$("#codeInput").blur(function(){
VaildateInput("codeInput");
if($(this).val() == ""||$("#codeInput").val()==null) {
$(this).val("请输入验证码");
}
});
$("#regestButton").click(function(){//注册按钮被点击的时候
check();
});
}
/**
* 检测输入的合法性函数
*/
function VaildateInput(sType) {
if (sType == "user") {
$("#userspan").html("正确").css("color","blue");
if($("#user").val() == null || $("#user").val() == ""){
$("#userspan").html("用户名不能为空").css("color","red");
return false;
}else {
jQuery.post("http://localhost:8080/xiaoyou/servlet/CheckUser",
{"user":$("#user").val()},
function(data){
if(data=="ok"){
$("#userspan").html("正确").css("color","blue");
}else if(data=="error"){
$("#userspan").html("用户名已经存在").css("color","red");
return false;
}
},"text",false);
}
}else if(sType == "password"){
$("#passwordspan").html("正确").css("color","blue");
if($("#password").val() == null || $("#password").val() == ""){
$("#passwordspan").html("密码不可以为空").css("color","red");
return false;
}else{
}
}else if(sType == "password1"){
$("#password1span").html("正确").css("color","blue");
if($("#password").val() != $("#password1").val()){
$("#password1span").html("两次密码不一致").css("color","red");
return false;
}else{
if($("#password1").val() == null || $("#password1").val() == ""){
$("#password1span").html("重复密码不可以为空").css("color","red");
return false;
}else{
}
}
}else if(sType == "email"){
$("#emailspan").html("正确").css("color","blue");
if($("#email").val() == null || $("#email").val() == ""){
$("#emailspan").html("邮箱地址不能为空").css("color","red");
return false;
}else {
var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
if (!reg.test($("#email").val())) {
$("#emailspan").html("邮箱格式不正确").css("color","red");
return false;
}else{
}
}
}else if(sType == "realname"){
$("#realnamespan").html("正确").css("color","blue");
if($("#realname").val() == null || $("#realname").val() == ""){
$("#realnamespan").html("真实姓名不能为空").css("color","red");
return false;
}else{
}
}else if(sType == "codeInput"){
$("#codeInputspan").html("正确").css("color","blue");
if($("#codeInput").val() == null || $("#codeInput").val() == ""||$("#codeInput").val() == "请输入验证码"){
$("#codeInputspan").html("验证码不能为空").css("color","red");
return false;
}else{
jQuery.post("http://localhost:8080/xiaoyou/servlet/CheckCode",
{"code":$("#codeInput").val()},
function(data){
if(data=="ok"){
$("#codeInputspan").html("正确").css("color","blue");
}else if(data=="error"){
$("#codeInputspan").html("您输入的验证码不正确").css("color","red");
return false;
}
},"text",false);
}
}
return true;
}
/**
* 点击注册按钮触发的事件
* 通过ajax传值给后台action
*/
function check(){
if(VaildateInput('user')){
if(VaildateInput('password')){
if(VaildateInput('password1')){
if( VaildateInput('email')){
if(VaildateInput('realname')){
if(VaildateInput('codeInput')){
var preData = $('#registerfrom').serialize();
$.ajax({
url: 'http://localhost:8080/xiaoyou/servlet/regest',
data:preData,
type: "POST",
async: false,
dataType: "text",
success: function(data){
//每次访问完注册的时候,验证码都要变
$("#IdentifyingCode").attr("src","http://localhost:8080/xiaoyou/servlet/IdentifyingCode?"+new Date());
if(data == "ok"){
location.href = "http://localhost:8080/xiaoyou/page/jsp/message.jsp";
}else{
alert("注册失败");
}
}
});
}
}
}
}
}
}
}
本文介绍了一种基于Java的验证码生成及校验方法,详细展示了如何在Servlet中生成包含随机字符和干扰线的图片验证码,并在用户输入后进行有效性检查。同时,提供了完整的代码实例,包括生成验证码的Servlet、调用验证码的JSP页面以及用于检测验证码的JavaScript脚本。

6814

被折叠的 条评论
为什么被折叠?



