前言
很多新手对图片验证码不是很了解,所以本文尝试通过一个简单的 jsp 小程序来实现验证码功能。文中给出了详细的示例代码,文末给出了完整实例代码的下载地址,下面话不多说了,来一起看看详细的介绍吧。
效果图
示例代码
前台代码如下:
<form action="action.jsp" method="post"> <label> 用户名: <input type="text" name="name" data-singletips="请输入用户名" value="admin" /> </label> <label> 密码: <input type="password" name="password" /> </label> <!-- 验证码 --> <label class="captchacode"> 验证码: <img src="img.jsp" style="cursor: pointer;" onclick="this.src=this.src + '?' + new date().valueof();" /> <input type="text" name="captchaimgcode" /> </label> <div> <input type="submit" value="登录" /> </div> </form>
验证码图片从何而来? img.jsp 是也:
<%@include file="captcha.jsp"%> <% init(pagecontext);// 加载图片 %>
返回图片的数据流。
action.jsp 这里不作用户名或密码的检验,只是单纯验证码检验。
如果输入验证码通过,显示如下:
反之,给出已捕获的异常:
action.jsp 就是调用 captcha.jsp 里面的 ispass(pagecontext, captchaimgcode) 方法,以及捕获已知异常。
<%@page pageencoding="utf-8"%>
<%@include file="captcha.jsp"%>
<%
string captchaimgcode = request.getparameter("captchaimgcode");
try {
if (ispass(pagecontext, captchaimgcode)) {
out.println("验证码通过!");
}
} catch (throwable e) {
out.println(e);
}
%>
核心 captcha,jsp 代码:
<%@page pageencoding="utf-8" import="java.io.ioexception, java.awt.*, java.awt.image.bufferedimage, java.util.random, javax.imageio.imageio"%>
<%!
// 定义captcha 类
public static class captcha {
/**
* 默认宽度 60
*/
private int width = 60;
/**
* 默认高度 20
*/
private int height = 20;
/**
* 验证码
*/
private string code;
/**
* 生成验证码图片
*
* @return 图片对象
*/
public bufferedimage get() {
bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb);// 在内存中创建图像
graphics g;
g = image.getgraphics(); // 获取图形上下文
g.setcolor(getrandcolor(200, 250)); // 设定背景
g.fillrect(0, 0, width, height);
g.setfont(new font("times new roman", font.plain, 18)); // 设定字体
g.setcolor(getrandcolor(160, 200));
random random = new random();// 随机产生干扰线
for (int i = 0; i < 155; i++) {
int x = random.nextint(width), y = random.nextint(height);
int xl = random.nextint(12), yl = random.nextint(12);
g.drawline(x, y, x + xl, y + yl);
}
string srand = ""; // 随机产生4位验证码
for (int i = 0; i < 4; i++) {
string rand = string.valueof(random.nextint(10));
srand += rand;
g.setcolor(new color(20 + random.nextint(110), 20 + random.nextint(110), 20 + random.nextint(110))); // 将认证码显示到图象中
g.drawstring(rand, 13 * i + 6, 16);// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
}
// 将认证码存入session
// session.setattribute("rand", srand);
setcode(srand);
g.dispose();// 图象生效
return image;
}
/**
* 生成随机颜色
*
* @param fc
* @param bc
* @return
*/
private color getrandcolor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
random random = new random();
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);
}
/**
* 获取高度
*
* @return
*/
public int getheight() {
return height;
}
/**
* 设置高度
*
* @param height
* 高度
*/
public void setheight(int height) {
this.height = height;
}
/**
* 获取验证码
*
* @return
*/
public string getcode() {
return code;
}
/**
* 设置验证码
*
* @param code
* 验证码
*/
public void setcode(string code) {
this.code = code;
}
/**
* 获取宽度
*
* @return
*/
public int getwidth() {
return width;
}
/**
* 设置宽度
*
* @param width
* 宽度
*/
public void setwidth(int width) {
this.width = width;
}
}
/**
* session 的键值
*/
public static final string session_key = "rand";
/**
* 显示验证码图片并将认证码存入 session
*
* @param response
* 响应对象
* @param session
* 会话对象
*/
public static void init(httpservletresponse response, httpsession session) {
captcha img = new captcha();
// 不用缓存
response.setheader("pragma", "no-cache");
response.setheader("cache-control", "no-cache");
response.setdateheader("expires", 0);
response.setcontenttype("image/jpg");
try {
imageio.write(img.get(), "jpeg", response.getoutputstream());
/*
* 加上下面代码,运行时才不会出现java.lang.illegalstateexception: getoutputstream() has already been called ..........等异常
* response.getoutputstream().flush();
* response.getoutputstream().close();
* response.flushbuffer();
*/
// jsp内置对象out和response.getwrite()的区别,两者的主要区别:1. 这两个对象的类型是完全不同的……
// response.getwriter();
// http://blog.sina.com.cn/s/blog_7217e4320101l8gq.html
// http://www.jb51.net/kf/201109/103284.html
// pagecontext.getout().clear();
} catch (ioexception e) {
e.printstacktrace();
}
session.setattribute(session_key, img.getcode()); // 将认证码存入 session
system.out.println("生成验证码:" + img.getcode());
}
/**
* 显示验证码图片并将认证码存入 session(for jsp)
*
* @param pagecontext
* 页面上下文对象
*/
public static void init(pagecontext pagecontext) {
init((httpservletresponse) pagecontext.getresponse(), pagecontext.getsession());
}
/**
* 判断用户输入的验证码是否通过
*
* @param pagecontext
* 页面上下文对象
* @return true 表示通过
* @throws throwable
*/
public static boolean ispass(pagecontext pagecontext, string code) throws throwable {
boolean iscaptchapass = false;
string rand = (string) pagecontext.getsession().getattribute(session_key);
system.out.println("rand:" + rand);
system.out.println("captchacode:" + code);
if (rand == null)
throw new unsupportedoperationexception("请刷新验证码。");
else if (code == null || code.equals("")) {
throw new illegalargumentexception("没提供验证码参数");
} else {
iscaptchapass = rand.equals(code);
if (!iscaptchapass)
throw new illegalaccesserror("验证码不正确");
}
return iscaptchapass;
}
%>
完整代码下载:http://xiazai.jb51.net/201707/yuanma/captcha(jb51.net).rar
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对硕编程的支持。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!