欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用jsp页面生成随机的验证数字码示例

程序员文章站 2023-11-27 16:34:46
checknum.jsp 复制代码 代码如下: <%@ page language="java" import="java.util.*,java.sql.*" pa...
checknum.jsp
复制代码 代码如下:

<%@ page language="java" import="java.util.*,java.sql.*" pageencoding="utf-8"%>
<%@ page contenttype="image/jpeg" import="java.awt.*,java.awt.image.*,javax.imageio.*"%>

<%
string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>

<%!
color getrandcolor(int fc,int bc)//给定范围随机选颜色
{
random random = new random();
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);
}
%>
<%
response.setheader("pragma","no-cache");//设置页面不缓冲
response.setheader("cache-control","no-cache");
response.setdateheader("expires",0);
int width=60,height=20;
bufferedimage image = new bufferedimage(width,height,bufferedimage.type_int_rgb);
graphics g = image.getgraphics();//获取图像上下文
random random = new random();//生成随机对象
g.setcolor(getrandcolor(200,250));
g.fillrect(0,0,width,height);
g.setfont(new font("times new roman",font.plain,18));//设置字体
for(int i=0;i<155;i++)
{
int x=random.nextint(width);
int y=random.nextint(height);
int x1 = random.nextint(12);
int y1 = random.nextint(12);
g.drawline(x,y,x+x1,y+y1);
}
//随机产生验证码
string srand = "";
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);
//图像生效
g.dispose();
//输出图像到页面
imageio.write(image,"jpeg",response.getoutputstream());
out.clear();
out = pagecontext.pushbody();

%>

可以在登录login.jsp下直接通过: 这种格式调用;
验证码:<input class="imgbutton" name="checknum" type="text" size="15" id ="checknum" maxlength="4"/>
<img src="checknum.jsp" alt="change" border="1" onclick="changechecknum()"/><br/>
<input type="submit" name="submit" value="login"/>