@webservlet("/getcodeservlet")
public class getcodeservlet extends httpservlet {
//验证码的宽、高
private static int width=80;
private static int height=25;
//绘制背景
private void drawbg(graphics g){
//rgb
g.setcolor(new color(128, 128, 128));
//绘制矩形。x,y,wigth,height
g.fillrect(0,0,width,height);
//随机绘制100个干扰点
random random=new random();
for (int i=0;i<100;i++){
//产生(0,1)上的小数,*width|height,再取整也行
int x=random.nextint(width);
int y=random.nextint(height);
g.drawoval(x,y,1,1);
//干扰点的颜色也可以随机,随机产生red,green,blue即可
//g.setcolor(new color(red,green,blue));
}
}
//绘制验证码
private void drawcode(graphics g,char[] code){
g.setcolor(color.black);
//字体、样式(多个时竖线分隔)、字号
g.setfont(new font("serif",font.italic|font.bold,18));
//在不同位置绘制验证码字符,参数:要绘制的string、横、纵坐标。+""是为了char转string。
g.drawstring(code[0]+"",1,17);
g.drawstring(code[1]+"",16,15);
g.drawstring(code[2]+"",31,18);
g.drawstring(code[3]+"",46,16);
}
//随机产生4位验证码
private char[] getcode(){
string chars="0123456789qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm";
char[] code=new char[4];
random random=new random();
for (int i=0;i<4;i++){
//[0,62)
int index= random.nextint(62);
code[i]=chars.charat(index);
}
return code;
}
protected void dopost(httpservletrequest request, httpservletresponse response) throws ioexception {
httpsession session = request.getsession();
servletoutputstream sos = response.getoutputstream();
response.setcontenttype("image/jpeg");
//设置浏览器不缓存此图片
response.setheader("pragma","no-cache");
response.setheader("cache-control","no-cache");
response.setdateheader("expires",0);
//创建内存图片
bufferedimage bufferedimage = new bufferedimage(width, height, type_int_rgb);
graphics g= bufferedimage.getgraphics();
char[] code=getcode();
//将验证码放到session域中。session对象要在提交响应之前获得
session.setattribute("code",new string(code));
drawbg(g);
drawcode(g,code);
g.dispose();
//将图片输出到浏览器
bytearrayoutputstream baos = new bytearrayoutputstream();
imageio.write(bufferedimage,"jpeg",baos);
baos.writeto(sos);
baos.close();
sos.close();
}
protected void doget(httpservletrequest request, httpservletresponse response) throws ioexception {
dopost(request,response);
}
}
@webservlet("/loginservlet")
public class loginservlet extends httpservlet {
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
response.setcontenttype("text/html;charset=utf-8");
httpsession session = request.getsession();
string truecode= (string) session.getattribute("code");
string code=request.getparameter("code");
if (code.equals(truecode)){
response.getwriter().write("验证码正确");
}
else {
response.getwriter().write("验证码错误");
}
}
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
dopost(request,response);
}
}