JSP + Servlet实现生成登录验证码示例
程序员文章站
2023-01-03 23:27:27
随机生成四位数验证码,包括汉字,数字,英文大小写。
1.servlet类
package servlet;
import java.awt.basicst...
随机生成四位数验证码,包括汉字,数字,英文大小写。
1.servlet类
package servlet; import java.awt.basicstroke; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.graphics2d; import java.awt.geom.affinetransform; import java.awt.geom.line2d; import java.awt.image.bufferedimage; import java.io.ioexception; import java.io.printwriter; import java.util.random; import javax.imageio.imageio; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; public class picturecheckcode extends httpservlet { private static final long serialversionuid = 1l; public picturecheckcode() { super(); } public void destroy() { super.destroy(); } public void init() throws servletexception { super.init(); } /*该方法主要作用是获得随机生成的颜色*/ public color getrandcolor(int s,int e){ random random=new random (); if(s>255) s=255; if(e>255) e=255; int r,g,b; r=s+random.nextint(e-s); //随机生成rgb颜色中的r值 g=s+random.nextint(e-s); //随机生成rgb颜色中的g值 b=s+random.nextint(e-s); //随机生成rgb颜色中的b值 return new color(r,g,b); } public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { system.out.println("this is doget method"); this.dopost(request, response); } 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); //指定生成的响应图片,一定不能缺少这句话,否则错误. response.setcontenttype("image/jpeg"); int width=80,height=35; //指定生成验证码的宽度和高度 bufferedimage image=new bufferedimage(width,height,bufferedimage.type_int_rgb); //创建bufferedimage对象,其作用相当于一图片 graphics g=image.getgraphics(); //创建graphics对象,其作用相当于画笔 graphics2d g2d=(graphics2d)g; //创建grapchics2d对象 random random=new random(); font mfont=new font("楷体",font.bold,16); //定义字体样式 g.setcolor(getrandcolor(200,250)); g.fillrect(0, 0, width, height); //绘制背景 g.setfont(mfont); //设置字体 g.setcolor(getrandcolor(180,200)); //绘制100条颜色和位置全部为随机产生的线条,该线条为2f for(int i=0;i<100;i++){ int x=random.nextint(width-1); int y=random.nextint(height-1); int x1=random.nextint(6)+1; int y1=random.nextint(12)+1; basicstroke bs=new basicstroke(2f,basicstroke.cap_butt,basicstroke.join_bevel); //定制线条样式 line2d line=new line2d.double(x,y,x+x1,y+y1); g2d.setstroke(bs); g2d.draw(line); //绘制直线 } //输出由英文,数字,和中文随机组成的验证文字,具体的组合方式根据生成随机数确定。 string srand=""; string ctmp=""; int itmp=0; //制定输出的验证码为四位 for(int i=0;i<4;i++){ switch(random.nextint(3)){ case 1: //生成a-z的字母 itmp=random.nextint(26)+65; ctmp=string.valueof((char)itmp); break; case 2: //生成汉字 string[] rbase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; //生成第一位区码 int r1=random.nextint(3)+11; string str_r1=rbase[r1]; //生成第二位区码 int r2; if(r1==13){ r2=random.nextint(7); }else{ r2=random.nextint(16); } string str_r2=rbase[r2]; //生成第一位位码 int r3=random.nextint(6)+10; string str_r3=rbase[r3]; //生成第二位位码 int r4; if(r3==10){ r4=random.nextint(15)+1; }else if(r3==15){ r4=random.nextint(15); }else{ r4=random.nextint(16); } string str_r4=rbase[r4]; //将生成的机内码转换为汉字 byte[] bytes=new byte[2]; //将生成的区码保存到字节数组的第一个元素中 string str_12=str_r1+str_r2; int templow=integer.parseint(str_12, 16); bytes[0]=(byte) templow; //将生成的位码保存到字节数组的第二个元素中 string str_34=str_r3+str_r4; int temphigh=integer.parseint(str_34, 16); bytes[1]=(byte)temphigh; ctmp=new string(bytes); break; default: itmp=random.nextint(10)+48; ctmp=string.valueof((char)itmp); break; } srand+=ctmp; color color=new color(20+random.nextint(110),20+random.nextint(110),random.nextint(110)); g.setcolor(color); //将生成的随机数进行随机缩放并旋转制定角度 ps.建议不要对文字进行缩放与旋转,因为这样图片可能不正常显示 /*将文字旋转制定角度*/ graphics2d g2d_word=(graphics2d)g; affinetransform trans=new affinetransform(); trans.rotate((45)*3.14/180,15*i+8,7); /*缩放文字*/ float scalesize=random.nextfloat()+0.8f; if(scalesize>1f) scalesize=1f; trans.scale(scalesize, scalesize); g2d_word.settransform(trans); g.drawstring(ctmp, 15*i+18, 14); } httpsession session=request.getsession(true); session.setattribute("randcheckcode", srand); system.out.println(srand); g.dispose(); //释放g所占用的系统资源 imageio.write(image,"jpeg",response.getoutputstream()); //输出图片 } }
2.web.xml配置
<servlet> <description>this is the description of my j2ee component</description> <display-name>this is the display name of my j2ee component</display-name> <servlet-name>picturecheckcode</servlet-name> <servlet-class>servlet.picturecheckcode</servlet-class> </servlet> <servlet-mapping> <servlet-name>picturecheckcode</servlet-name> <url-pattern>/picturecheckcode</url-pattern> </servlet-mapping>
3.jsp页面输出验证码
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>登录页面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <script language="javascript"> function myreload() { document.getelementbyid("createcheckcode").src = document .getelementbyid("createcheckcode").src + "?nocache=" + new date().gettime(); } </script> </head> <body> <form action="loginservlet" method="get"> <p class="font tdheight"> 验证码:<input type="text" name="checkcode" style="width:70px;height:35px;"> <img src="picturecheckcode" id="createcheckcode" align="middle" style="margin-top:-10px;"> <br> <a href="" onclick="myreload()" style="font-size:12px;color:red;margin-left:156px;"> 看不清,换一个</a> </p> <br><input type="submit" value="提交" class="font" style="width:240px;height:35px;background:#f19e28"> </form> </body> </html>
4.后台servlet判断验证码是否与输入一致
通过request.getparameter(“checkcode”)获取输入验证码,与session.getattribute(“randcheckcode”)比较是否一致。
public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string code = request.getparameter("checkcode"); httpsession session = request.getsession(); if (!code.equals(session.getattribute("randcheckcode"))) { request.setattribute("errormsg", "验证码不正确"); } system.out.println(request.getattribute("errormsg")); }
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。