verifycode(verifycodeservlet)

http://www.itjxue.com  2023-01-26 21:02  来源:未知  点击次数: 

Java如何实现验证码验证功能

Java如何实现验证码验证功能呢?日常生活中,验证码随处可见,他可以在一定程度上保护账号安全,那么他是怎么实现的呢?

Java实现验证码验证功能其实非常简单:用到了一个Graphics类在画板上绘制字母,随机选取一定数量的字母随机生成,然后在画板上随机生成几条干扰线。

首先,写一个验证码生成帮助类,用来绘制随机字母:

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;

public?final?class?GraphicHelper?{

/**

*?以字符串形式返回生成的验证码,同时输出一个图片

*

*?@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?};

//?在?"画板"上生成干扰线条?(?50?是线条个数)

for?(int?i?=?0;?i??50;?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("Comic?Sans?MS",?Font.BOLD,?30));

for?(int?i?=?0;?i??6;?i++)?{

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),?height?-?(height?/?3));

}

graphic.dispose();

try?{

ImageIO.write(image,?imgType,?output);

}?catch?(IOException?e)?{

e.printStackTrace();

}

return?sb.toString();

}

}?

接着,创建一个servlet,用来固定图片大小,以及处理验证码的使用场景,以及捕获页面生成的验证码(捕获到的二维码与用户输入的验证码一致才能通过)。

import?java.io.OutputStream;

import?javax.servlet.ServletException;

import?javax.servlet.annotation.WebServlet;

import?javax.servlet.http.HttpServlet;

import?javax.servlet.http.HttpServletRequest;

import?javax.servlet.http.HttpServletResponse;

import?javax.servlet.http.HttpSession;

@WebServlet(urlPatterns?=?"/verify/regist.do"?)

public?class?VerifyCodeServlet?extends?HttpServlet?{

private?static?final?long?serialVersionUID?=?3398560501558431737L;

@Override

protected?void?service(HttpServletRequest?request,?HttpServletResponse?response)

throws?ServletException,?IOException?{

//?获得?当前请求?对应的?会话对象

HttpSession?session?=?request.getSession();

//?从请求中获得?URI?(?统一资源标识符?)

String?uri?=?request.getRequestURI();

System.out.println("hello?:?"?+?uri);

final?int?width?=?180;?//?图片宽度

final?int?height?=?40;?//?图片高度

final?String?imgType?=?"jpeg";?//?指定图片格式?(不是指MIME类型)

final?OutputStream?output?=?response.getOutputStream();?//?获得可以向客户端返回图片的输出流

//?(字节流)

//?创建验证码图片并返回图片上的字符串

String?code?=?GraphicHelper.create(width,?height,?imgType,?output);

System.out.println("验证码内容:?"?+?code);

//?建立?uri?和?相应的?验证码?的关联?(?存储到当前会话对象的属性中?)

session.setAttribute(uri,?code);

System.out.println(session.getAttribute(uri));

}

}?

接着写一个HTML注册页面用来检验一下:

html

head

meta?charset="UTF-8"

title注册/title

link?rel="stylesheet"?href="styles/general.css"

link?rel="stylesheet"?href="styles/cell.css"

link?rel="stylesheet"?href="styles/form.css"

script?type="text/javascript"?src="js/ref.js"/script

style?type="text/css"?

.logo-container?{

margin-top:?50px?;

}

.logo-container?img?{

width:?100px?;

}

.message-container?{

height:?80px?;

}

.link-container?{

height:?40px?;

line-height:?40px?;

}

.link-container?a?{

text-decoration:?none?;

}

/style

/head

body

div?class="container?form-container"

form?action="/wendao/regist.do"?method="post"

div?class="form"?!--?注册表单开始?--

div?class="form-row"

span?class="cell-1"

i?class="fa?fa-user"/i

/span

span?class="cell-11"?style="text-align:?left;"

input?type="text"?name="username"?placeholder="请输入用户名"

/span

/div

div?class="form-row"

span?class="cell-1"

i?class="fa?fa-key"/i

/span

span?class="cell-11"?style="text-align:?left;"

input?type="password"?name="password"?placeholder="请输入密码"

/span

/div

div?class="form-row"

span?class="cell-1"

i?class="fa?fa-keyboard-o"/i

/span

span?class="cell-11"?style="text-align:?left;"

input?type="password"?name="confirm"?placeholder="请确认密码"

/span

/div

div?class="form-row"

span?class="cell-7"

input?type="text"?name="verifyCode"?placeholder="请输入验证码"

/span

span?class="cell-5"?style="text-align:?center;"

img?src="/demo/verify/regist.do"?onclick="myRefersh(this)"

/span

/div

div?class="form-row"?style="border:?none;"

span?class="cell-6"?style="text-align:?left"

input?type="reset"?value="重置"

/span

span?class="cell-6"??style="text-align:right;"

input?type="submit"?value="注册"

/span

/div

/div?!--?注册表单结束?--

/form

/div

/body

/html

效果如下图:

在控制台接收到的图片中验证码的变化如下:

当点击刷新页面的时候,验证码也会随着变化,但我们看不清验证码时,只要点击验证码就会刷新,这样局部的刷新可以用JavaScript来实现。

在img

src="/demo/verify/regist.do"中,添加一个问号和一串后缀数字,当刷新时让后缀数字不断改变,那么形成的验证码也会不断变化,我们可以采用的一种办法是后缀数字用date代替,date获取本机时间,时间是随时变的,这样就保证了刷新验证码可以随时变化。

代码如下:

function?myRefersh(?e?)?{

const?source?=?e.src?;?//?获得原来的?src?中的内容

//console.log(?"source?:?"?+?source??)?;

var?index?=?source.indexOf(?"?"?)?;??//?从?source?中寻找???第一次出现的位置?(如果不存在则返回?-1?)

//console.log(?"index?:?"?+?index??)?;

if(?index??-1?)?{?//?如果找到了????就进入内部

var?s?=?source.substring(?0?,?index?)?;?//?从?source?中截取?index?之前的内容?(?index?以及?index?之后的内容都被舍弃?)

//console.log(?"s?:?"?+?s??)?;

var?date?=?new?Date();?//?创建一个?Date?对象的?一个?实例

var?time?=?date.getTime()?;?//?从?新创建的?Date?对象的实例中获得该时间对应毫秒值

e.src?=?s?+?"?time="?+?time?;?//?将?加了?尾巴?的?地址?重新放入到?src?上

//console.log(?e.src?)?;

}?else?{

var?date?=?new?Date();

e.src?=?source?+?"?time="?+?date.getTime();

}

}

如回答不详细可追问

php封装一个用户类,里面有登录注册方法,这个要怎么写

第一步:login.php

//登陆方法

public function login(){

//如果用户名和密码为空,则返回登陆页面

if(empty($_POST['username']) || empty($_POST['password'])){

$data['verifycode'] = rand(1000,9999);//生成一个四位数字的验证码

//将验证码放入session中,注意:参数是数组的格式

$this-session-set_userdata($data);

//注意:CI框架默认模板引擎解析的模板文件中变量不需要$符号

//$this-parser-parse("admin/login",$data);

//smarty模板变量赋值

$this-tp-assign("verifycode",$data['verifycode']);

//ci框架在模板文件中使用原生态的PHP语法输出数据

//$this-load-view('login',$data);//登陆页面,注意:参数2需要以数组的形式出现

//显示smarty模板引擎设定的模板文件

$this-tp-display("admin/login.php");

}else{

$username = isset($_POST['username'])!empty($_POST['username'])?trim($_POST['username']):'';//用户名

$password = isset($_POST['password'])!empty($_POST['password'])?trim($_POST['password']):'';//密码

$verifycode = isset($_POST['verifycode'])!empty($_POST['verifycode'])?trim($_POST['verifycode']):'';//验证码

//做验证码的校验

if($verifycode == $this-session-userdata('verifycode')){

//根据用户名及密码获取用户信息,注意:参数2是加密的密码

$user_info=$this-user_model-check_user_login($username,md5($password));

if($user_info['user_id'] 0){

//将用户id、username、password放入cookie中

//第一种设置cookie的方式:采用php原生态的方法设置的cookie的值

//setcookie("user_id",$user_info['user_id'],86500);

//setcookie("username",$user_info['username'],86500);

//setcookie("password",$user_info['password'],86500);

//echo $_COOKIE['username'];

//第二种设置cookie的方式:通过CI框架的input类库

$this-input-set_cookie("username",$user_info['username'],3600);

$this-input-set_cookie("password",$user_info['password'],3600);

$this-input-set_cookie("user_id",$user_info['user_id'],3600);

//echo $this-input-cookie("password");//适用于控制器

//echo $this-input-cookie("username");//适用于控制器

//echo $_COOKIE['username'];//在模型类中可以通过这种方式获取cookie值

//echo $_COOKIE['password'];//在模型类中可以通过这种方式获取cookie值

//第三种设置cookie的方式:通过CI框架的cookie_helper.php函数库文件

//这种方式不是很灵验,建议大家采取第二种方式即可

//set_cookie("username",$user_info['username'],3600);

//echo get_cookie("username");

//session登陆时使用:将用户名和用户id存入session中

//$data['username']=$user_info['username'];

//$data['user_id']=$user_info['user_id'];

//$this-session-set_userdata($data);

//跳转到指定页面

//注意:site_url()与base_url()的区别,前者带index.php,后者不带index.php

header("location:".site_url("index/index"));

}

}else{

//跳转到登陆页面

header("location:".site_url("common/login"));

}

}

}

}

第二步:User_model.php

//cookie登陆:检测用户是否登陆,如果cookie值失效,则返回false,如果cookie值未失效,则根据cookie中的用户名和密码从数据库中获取用户信息,如果能获取到用户信息,则返回查询到的用户信息,如果没有查询到用户信息,则返回0

public function is_login(){

//获取cookie中的值

if(empty($_COOKIE['username']) || empty($_COOKIE['password'])){

$user_info = false;

}else{

$user_info=$this-check_user_login($_COOKIE['username'],$_COOKIE['password']);

}

return $user_info;

}

//根据用户名及加密密码从数据库中获取用户信息,如果能获取到,则返回获取到的用户信息,否则返回false,注意:密码为加密密码

public function check_user_login($username,$password){

//这里大家要注意:$password为md5加密后的密码

//$this-db-query("select * from ");

//快捷查询类的使用:能为我们提供快速获取数据的方法

//此数组为查询条件

//注意:关联数组

$arr=array(

'username'=$username,//用户名

'password'=$password,//加密密码

'status'=1 //账户为开启状态

);

//在database.php文件中已经设置了数据表的前缀,所以此时数据表无需带前缀

$query = $this-db-get_where("users",$arr);

//返回二维数组

//$data=$query-result_array();

//返回一维数组

$user_info=$query-row_array();

if(!empty($user_info)){

return $user_info;

}else{

return false;

}

}

第三步:其它控制器:

public function __construct(){

//调用父类的构造函数

parent::__construct();

$this-load-library('tp'); //smarty模板解析类

$this-load-helper('url'); //url函数库文件

$this-load-model("user_model");//User_model模型类实例化对象

$this-cur_user=$this-user_model-is_login();

if($this-cur_user === false){

header("location:".site_url("common/login"));

}else{

//如果已经登陆,则重新设置cookie的有效期

$this-input-set_cookie("username",$this-cur_user['username'],3600);

$this-input-set_cookie("password",$this-cur_user['password'],3600);

$this-input-set_cookie("user_id",$this-cur_user['user_id'],3600);

}

$this-load-library('pagination');//分页类库

$this-load-model("role_model");//member_model模型类

$this-load-model("operation_model");//引用operation_model模型

$this-load-model("object_model");//引用object_model模型

$this-load-model("permission_model");//引用permission_model模型

}

asp的验证码控件怎么做

%dim rndnum,verifycode

Randomize

Do While Len(rndnum)4

num1=CStr(Chr((57-48)*rnd+48))

rndnum=rndnumnum1

loop

session("verifycode")=rndnum

%然后做两个验证码input一个用户输入一个是隐藏验证域做比较用

微信号被封了手机号不能收到短信验证怎么办

解封方法,前提是这两种情况的账号你都有,假设第一种情况的微信号是A账号,第二种情况的微信号是B账号:

因为A账号能登陆,大号一般不会封,大号转账给A0.01分钱。A收款。

B账号登陆,提示账号违规,进入解封界面,输入A微信号,给A解封,输入接码平台手机号,接码解封,提示成功。

补充:@b547758741吧友提供了网页解封地址:这样估计不用B账号就行了,直接在网页上解封就可以了.

A账号退出登陆,重新登陆,首次给好友发信息可能会发不出去,再发就成功了,解封成功.

现在微信违规封号有两种模式:

账号能登陆,微信团队发信息,提示你部分功能受限制,让你尝试自助解封。这种情况没法加好友,没法关注公众号,没法发信息,就只能登陆,收信息。

一打开微信就提示账号违规,直接跳转到登陆页面。你登陆会提示你解封。

根据php判断验证码文件怎么写验证码文件

我把我网站的验证码流程贴出来,供你参考,希望采纳。

验证码前台

============================================

input name="yzm" type="text" style="width:70px" maxlength="4" class="dfinput yzm_note empty" ok="" err="验证码不能为空" tip="请输入验证码,不区分大小写" /

验证码触发

============================================

//验证码

$(".yzm_note").live("focus", function(){

if($(this).parent().find(".yzm_img").length == 0){

$(this).after('img class="yzm_img" src="'+site_domain+'inc/captcha.php?mo='+Math.random()+'" align="absmiddle" /a class="yzm_a" href="javascript:;" onclick="$(\'.yzm_img\').attr({\'src\' : \''+site_domain+'inc/captcha.php?mo=\'+Math.random()});" title="看不清楚,点击换一张"/a');

}

});

验证码后端验证

============================================

//验证码

if(empty($_POST['yzm']) || empty($_SESSION['info_yzm']) || substr(md5(strtolower($_POST['yzm'])), 0, 12) != $_SESSION['info_yzm']){

unset($_SESSION['info_yzm']);

echoHtml('script type="text/javascript"alert("验证码错误");/script');

exit;

}

unset($_SESSION['info_yzm']);

成功应用的网站 发布信息网 baijiaxx.com

JAVAWEB项目怎么实现验证码

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;

public?class?Code?{

???

????//?图片的宽度。

????private?int?width?=?160;

????//?图片的高度。

????private?int?height?=?38;

????//?验证码字符个数

????private?int?codeCount?=?4;

????//?验证码干扰线数

????private?int?lineCount?=?20;

????//?验证码

????private?String?code?=?null;

????//?验证码图片Buffer

????private?BufferedImage?buffImg?=?null;

????Random?random?=?new?Random();

????

????private?boolean?type?=?false;

????public?Code()?{

???????

????}

????public?Code(int?width,?int?height)?{

????????this.width?=?width;

????????this.height?=?height;

????}

????public?Code(int?width,?int?height,?int?codeCount)?{

????????this.width?=?width;

????????this.height?=?height;

????????this.codeCount?=?codeCount;

????}

????public?Code(int?width,?int?height,?int?codeCount,?int?lineCount)?{

????????this.width?=?width;

????????this.height?=?height;

????????this.codeCount?=?codeCount;

????????this.lineCount?=?lineCount;

????}

????

????public?void?init(boolean?type){

???????this.type?=?type;

????}

????//?生成图片

????private?void?creatImage(boolean?type)?{

????????int?fontWidth?=?width?/?codeCount;//?字体的宽度

????????int?fontHeight?=?height?-?5;//?字体的高度

????????int?codeY?=?height?-?8;

????????//?图像buffer

????????buffImg?=?new?BufferedImage(width,?height,?BufferedImage.TYPE_INT_RGB);

????????Graphics?g?=?buffImg.getGraphics();

????????//Graphics2D?g?=?buffImg.createGraphics();

????????//?设置背景色

????????g.setColor(getRandColor(200,?250));

????????g.fillRect(0,?0,?width,?height);

????????

????????

????????

????????//?设置字体

????????Font?font?=?null;

????????if(!type)?font?=?new?Font("Fixedsys",?Font.BOLD,?fontHeight);

????????else?font?=?getFont(fontHeight);

????????g.setFont(font);

????????//?设置干扰线

????????for?(int?i?=?0;?i??lineCount/2;?i++)?{

????????????int?xs?=?random.nextInt(width);

????????????int?ys?=?random.nextInt(height);

????????????int?xe?=?xs?+?random.nextInt(width);

????????????int?ye?=?ys?+?random.nextInt(height);

????????????g.setColor(getRandColor(1,?255));

????????????if(!type)?g.drawLine(xs,?ys,?xe,?ye);

????????????else?shear(g,?width,?height,?getRandColor(1,?255))?;

????????}

????????//?添加噪点

????????float?yawpRate?=?0.01f;//?噪声率

????????int?area?=?(int)?(yawpRate?*?width?*?height);

????????for?(int?i?=?0;?i??area;?i++)?{

????????????int?x?=?random.nextInt(width);

????????????int?y?=?random.nextInt(height);

????????????buffImg.setRGB(x,?y,?random.nextInt(255));

????????}

????????String?str1?=?randomStr(codeCount);//?得到随机字符

????????this.code?=?str1;

????????for?(int?i?=?0;?i??codeCount;?i++)?{

????????????String?strRand?=?str1.substring(i,?i?+?1);

????????????g.setColor(getRandColor(1,?255));

????????????//?g.drawString(a,x,y);

????????????//?a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的?(x,?y)?位置处

????????????

????????????g.drawString(strRand,?i*fontWidth+3,?codeY);

????????}

????????

????}

????//?得到随机字符

????private?String?randomStr(int?n)?{

????????String?str1?=?"ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz1234567890";//I和l不要

????????String?str2?=?"";

????????int?len?=?str1.length()?-?1;

????????double?r;

????????for?(int?i?=?0;?i??n;?i++)?{

????????????r?=?(Math.random())?*?len;

????????????str2?=?str2?+?str1.charAt((int)?r);

????????}

????????return?str2;

????}

????//?得到随机颜色

????private?Color?getRandColor(int?fc,?int?bc)?{//?给定范围获得随机颜色

????????if?(fc??255)

????????????fc?=?255;

????????if?(bc??255)

????????????bc?=?255;

????????int?r?=?fc?+?random.nextInt(bc?-?fc);

????????int?g?=?fc?+?random.nextInt(bc?-?fc);

????????int?b?=?fc?+?random.nextInt(bc?-?fc);

????????return?new?Color(r,?g,?b);

????}

????

????/**

?????*?产生随机字体

?????*/

????private?Font?getFont(int?size)?{

????????Random?random?=?new?Random();

????????Font?font[]?=?new?Font[5];

????????font[0]?=?new?Font("Ravie",?Font.PLAIN,?size);

????????font[1]?=?new?Font("Antique?Olive?Compact",?Font.PLAIN,?size);

????????font[2]?=?new?Font("Fixedsys",?Font.PLAIN,?size);

????????font[3]?=?new?Font("Wide?Latin",?Font.PLAIN,?size);

????????font[4]?=?new?Font("Gill?Sans?Ultra?Bold",?Font.PLAIN,?size);

????????return?font[random.nextInt(5)];

????}

????

????//?扭曲方法

????private?void?shear(Graphics?g,?int?w1,?int?h1,?Color?color)?{

????????shearX(g,?w1,?h1,?color);

????????shearY(g,?w1,?h1,?color);

????}

????private?void?shearX(Graphics?g,?int?w1,?int?h1,?Color?color)?{

????????int?period?=?random.nextInt(2);

????????boolean?borderGap?=?true;

????????int?frames?=?1;

????????int?phase?=?random.nextInt(2);

????????for?(int?i?=?0;?i??h1;?i++)?{

????????????double?d?=?(double)?(period??1)

????????????????????*?Math.sin((double)?i?/?(double)?period

????????????????????????????+?(6.2831853071795862D?*?(double)?phase)

????????????????????????????/?(double)?frames);

????????????g.copyArea(0,?i,?w1,?1,?(int)?d,?0);

????????????if?(borderGap)?{

????????????????g.setColor(color);

????????????????g.drawLine((int)?d,?i,?0,?i);

????????????????g.drawLine((int)?d?+?w1,?i,?w1,?i);

????????????}

????????}

????}

????private?void?shearY(Graphics?g,?int?w1,?int?h1,?Color?color)?{

????????int?period?=?random.nextInt(40)?+?10;?//?50;

????????boolean?borderGap?=?true;

????????int?frames?=?20;

????????int?phase?=?7;

????????for?(int?i?=?0;?i??w1;?i++)?{

????????????double?d?=?(double)?(period??1)

????????????????????*?Math.sin((double)?i?/?(double)?period

????????????????????????????+?(6.2831853071795862D?*?(double)?phase)

????????????????????????????/?(double)?frames);

????????????g.copyArea(i,?0,?1,?h1,?0,?(int)?d);

????????????if?(borderGap)?{

????????????????g.setColor(color);

????????????????g.drawLine(i,?(int)?d,?i,?0);

????????????????g.drawLine(i,?(int)?d?+?h1,?i,?h1);

????????????}

????????}

????}

????

????public?void?write(OutputStream?sos)?throws?IOException?{

????????if(buffImg?==?null)?creatImage(type);

????????ImageIO.write(buffImg,?"png",?sos);

//????????JPEGImageEncoder?encoder?=?JPEGCodec.createJPEGEncoder(sos);

//????????encoder.encode(buffImg);

????????sos.close();

????}

????public?BufferedImage?getBuffImg()?{

???????if(buffImg?==?null)?creatImage(type);

????????return?buffImg;

????}

????public?String?getCode()?{

????????return?code.toLowerCase();

????}

????

????//使用方法

?/*public?void?getCode3(HttpServletRequest?req,?HttpServletResponse?response,HttpSession?session)?throws?IOException{

????????//?设置响应的类型格式为图片格式

????????????response.setContentType("image/jpeg");

????????????//禁止图像缓存。

????????????response.setHeader("Pragma",?"no-cache");

????????????response.setHeader("Cache-Control",?"no-cache");

????????????response.setDateHeader("Expires",?0);

????????????

????????????

????????????CreateImageCode?vCode?=?new?CreateImageCode(100,30,5,10);

????????????session.setAttribute("code",?vCode.getCode());

????????????vCode.write(response.getOutputStream());

????????????response.flushBuffer();

?????}*/

}

(责任编辑:IT教学网)

更多

推荐Flash实例教程文章