Struts2实现生成动态验证码并验证实例代码
一、基本流程:
产生一个验证码页面(很小)→嵌入到表单中→点击可以刷新页面→表单提交时验证。
二、方法:
1、定义TestAction,实现画图方法
packagecom.zhuguang.action; importjava.awt.Color; importjava.awt.Font; importjava.awt.Graphics; importjava.awt.image.BufferedImage; importjava.util.Map; importjavax.servlet.http.HttpServletResponse; importorg.apache.struts2.interceptor.ServletResponseAware; importorg.apache.struts2.interceptor.SessionAware; importcom.opensymphony.xwork2.ActionSupport; importcom.sun.image.codec.jpeg.JPEGCodec; importcom.sun.image.codec.jpeg.JPEGImageEncoder; publicclassTestActionextendsActionSupportimplementsSessionAware,ServletResponseAware { privateMap<String,Object>session; privateHttpServletResponseresponse; privatestaticfinallongserialVersionUID=1L; privateStringchknumber; @Override publicStringexecute()throwsException { response.setHeader("Cache-Control","no-cache"); intwidth=50;//图片宽度 intheight=20;//图片高度 BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphicsgraphics=image.createGraphics(); graphics.setColor(this.getColor());//背景颜色 graphics.fillRect(0,0,width,height); graphics.setFont(newFont("Arial",Font.BOLD,18)); graphics.setColor(this.getColor());//字的颜色 Stringnumber=String.valueOf(System.currentTimeMillis()%9000+1000);//生成四位随机数 session.put("randomCode",number);//写入session中 graphics.drawString(number,(int)(width*0.1),(int)(height*0.8)); graphics.dispose(); JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(response.getOutputStream()); encoder.encode(image); response.getOutputStream().flush();//刷新到页面生成图片 response.getOutputStream().close();//关闭writer returnnull; } privateColorgetColor(){ intred=(int)(Math.random()*1000%256); intgreen=(int)(Math.random()*1000%256); intblue=(int)(Math.random()*1000%256); returnnewColor(red,green,blue); } publicStringgetChknumber() { returnchknumber; } publicvoidsetChknumber(Stringchknumber) { this.chknumber=chknumber; } @Override publicvoidsetSession(Map<String,Object>session) { //TODOAuto-generatedmethodstub this.session=session; } @Override publicvoidsetServletResponse(HttpServletResponseresponse) { //TODOAuto-generatedmethodstub this.response=response; } }
注意用到session和response
2、在struts.xml文件中注册:
<actionname="randomCode"class="com.zhuguang.action.TestAction"> </action>
其中不返回任何信息,这样就不会跳转页面
3、jsp页面编写
<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <%@tagliburi="/struts-tags"prefix="s"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <scripttype="text/javascript"> <!-- functionreloadcode(obj,base){ varrand=newDate().getTime();//这里用当前时间作为参数加到url中,是为了使URL发生变化,这样验证码才会动态加载, //只是一个干扰作用,无确实意义,但却又非常巧妙,呵呵 obj.src=base+"randomCode.action?abc="+rand;//其实服务器端是没有abc的字段的。 } //--> </script> <title>测试页面</title> </head> <body> <formaction="testLogin"method="post"> Username<inputtype="text"name="name"><br> Password<inputtype="text"name="password"><br> 验证码:<inputtype="text"name="chknumber"id="chknumber"maxlength="4"class="chknumber_input"> <imgtitle="看不清楚请点击这里"width="50"height="20"src="<%=basePath%>randomCode.action"id="safecode"onclick="reloadcode(this,'<%=basePath%>')"/><br> <inputtype="submit"value="Loginin"> </form> </body> </html>
4、验证
(1)在Action中添加一个验证方法
publicStringtestLogin() { if(session.get("randomCode").equals(chknumber)) { returnSUCCESS; } else { returnERROR; } }
(2)在struts.xml中进行注册
<actionname="testLogin"class="com.zhuguang.action.TestAction"method="testLogin"> <resultname="success">success.jsp</result> <resultname="error">error.jsp</result> </action>
以上所述是小编给大家介绍的Struts2实现生成动态验证码并验证实例代码,希望对大家有所帮助!