此演示代码主要包括以下三部分:
1.checkcode.java:用于生成验证码
2.checkcodeservler
3.check.jsp 验证
下面是checkcode.java的内容:
//生成验证码,并返回随机生成的数字
public string getensure(int width, int height, outputstream os){
if (width <= 0)
width = 60;
if (height <= 0)
height = 20;
bufferedimage image = new bufferedimage(width, height,bufferedimage.type_int_rgb);
// 获取图形上下文
graphics g = image.getgraphics();
// 设定背景色
g.setcolor(new color(0xdccccc));
g.fillrect(0, 0, width, height);
// 画边框
g.setcolor(color.black);
g.drawrect(0, 0, width - 1, height - 1);
// 取随机产生的认证码
string strensure = "";
// 4代表4位验证码
for (int i = 0; i < 4; ++i){
strensure += maptable[(int) (maptable.length * math.random())];
}
// 将认证码显示到图象中
g.setcolor(color.red);
g.setfont(new font("atlantic inline", font.plain, 14));
// 画的具体坐标
string str = strensure.substring(0, 1);
g.drawstring(str, 8, 14);
str = strensure.substring(1, 2);
g.drawstring(str, 20, 15);
str = strensure.substring(2, 3);
g.drawstring(str, 35, 18);
str = strensure.substring(3, 4);
g.drawstring(str, 45, 15);
// 释放图形上下文
g.dispose();
try{
// 输出图象到页面
imageio.write(image, "jpeg", os);
} catch (ioexception e){
return "";
}
return strensure; //返回生成的随机数
}
再是checkcodeservlet的内容
public void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
//禁用缓存,每次访问此页面,都重新生成
response.setheader("pragma","no-cache");
response.setheader("cache-control","no-cache");
response.setdateheader("expires", 0);
//生成验证码的实例对象
checkcode ie = new checkcode();
//调用里面的方法,返回的是生成的验证码中的字符串
string str = ie.getensure(0,0,response.getoutputstream());
//获得session,并把字符串保存在session中,为后面的对比做基础
httpsession session = request.getsession();
session.setattribute("strensure", str);
}
然后是web.xml对servlet的配置
最后是jsp页面的引用
在jsp页面中,只需要将img的src的属性指向生成验证码的servlet就可以了,指向servle在web.xmlt映射的url。
如对本文有疑问, 点击进行留言回复!!
现在微服务这么火,你还不了解吗?阿里P8推荐的微服务学习指南
论文笔记:SlowFast Networks for Video Recognition
网友评论