JSP实现验证码 代码怎么写?
3个回答
展开全部
<%@pagecontentType=\"image/jpeg\"import=\"java.awt.*,java.awt.image.*,java.util.*,javax.imageio.* \"%> <%! //createbysmallnest //email:smallnest@gmail.com //website: www.kuaff.com //生成随机颜色 ColorgetRandColor(Randomrandom,intfc,intbc)...{ if(fc>255)fc=255; if(bc>255)bc=255; intr=fc+random.nextInt(bc-fc); intg=fc+random.nextInt(bc-fc); intb=fc+random.nextInt(bc-fc); returnnewColor(r,g,b); } %> <% //设置页面不缓存 response.setHeader(\"Pragma\",\"No-cache\"); response.setHeader(\"Cache-Control\",\"no-cache\"); response.setDateHeader(\"Expires\",0); //设置图片的长宽 intwidth=176,height=30; //设置备选汉字,剔除一些不雅的汉字 Stringbase=\"的一了是我不在人们有来他这上着个地到大里说就去子得也和那要下看天时过出小么起你都把好 还多没为又可家学只以主会样年想生同老中十从自面前头道它后然走很像见两用她国动进成回什边作对开而己 些现山民候经发工向事命给长水几义三声于高手知理眼志点心战二问但身方实吃做叫当住听革打呢真全才四已 所敌之最光产情路分总条白话东席次亲如被花口放儿常气五第使写军吧文运再果怎定许快明行因别飞外树物活 部门无往船望新带队先力完却站代员机更九您每风级跟笑啊孩万少直意夜比阶连车重便斗马哪化太指变社似士 者干石满日决百原拿群究各六本思解立河村八难早论吗根共让相研今其书坐接应关信觉步反处记将千找争领或 师结块跑谁草越字加脚紧爱等习阵怕月青半火法题建赶位唱海七女任件感准张团屋离色脸片科倒睛利世刚且由 送切星导晚表够整认响雪流未场该并底深刻平伟忙提确近亮轻讲农古黑告界拉名呀土清阳照办史改历转画造嘴 此治北必服雨穿内识验传业菜爬睡兴形量咱观苦体众通冲合破友度术饭公旁房极南枪读沙岁线野坚空收算至政 城劳落钱特围弟胜教热展包歌类渐强数乡呼性音答哥际旧神座章帮啦受系令跳非何牛取入岸敢掉忽种装顶急林 停息句区衣般报叶压慢叔背细\"; [Page] //备选汉字的长度 intlength=base.length(); //创建内存图像 BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //获取图形上下文 Graphicsg=image.getGraphics(); //创建随机类的实例 Randomrandom=newRandom(); //设定图像背景色(因为是做背景,所以偏淡) g.setColor(getRandColor(random,200,250)); g.fillRect(0,0,width,height); //备选字体 String[]fontTypes=...{ \"宋体\",\"新宋体\",\"黑体\",\"楷体\",\"隶书\"}; intfontTypesLength=fontTypes.length; //在图片背景上增加噪点 g.setColor(getRandColor(random,160,200)); g.setFont(newFont(\"TimesNewRoman\",Font.PLAIN,14)); for(inti=0;i<6;i++)...{ g.drawString(\"*********************************************\",0,5*(i+2)); } //取随机产生的认证码(6个汉字) //保存生成的汉字字符串 StringsRand=\"\"; for(inti=0;i<6;i++)...{ intstart=random.nextInt(length); Stringrand=base.substring(start,start+1); sRand+=rand; //设置字体的颜色 g.setColor(getRandColor(random,10,150)); //设置字体 g.setFont(newFont(fontTypes[random.nextInt(fontTypesLength)],Font.BOLD,18+random.nextInt(6))); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 很多新手对图片验证码不是很了解,今天我们就来看看一个实例吧,首先,先写一个动态图片生成的Servlet类,如下: package org.yuanliang; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class RandomCode extends HttpServlet { private static final long serialVersionUID = 1L; private static int WIDTH = 65;//设置图片的宽度 private static int HEIGHT = 22;//设置图片的高度 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); response.setContentType(\"image/jpeg\"); ServletOutputStream sos = response.getOutputStream(); response.setHeader(\"Pragma\", \"No-cache\"); response.setHeader(\"Cache-Control\", \"no-cache\"); response.setDateHeader(\"Expires\", 0); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); char[] rands = generateCheckCode(); drawBackground(g); drawRands(g, rands); g.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, \"JPEG\", bos); byte[] buf = bos.toByteArray(); response.setContentLength(buf.length); sos.write(buf); bos.close(); sos.close(); session.setAttribute(\"randomCode\", new String(rands)); } private void drawBackground(Graphics g) { g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, WIDTH, HEIGHT); for (int i = 0; i < 120; i++) { int x = (int) (Math.random() * WIDTH); int y = (int) (Math.random() * HEIGHT); int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); g.setColor(new Color(red, green, blue)); g.drawOval(x, y, 1, 0);[Page] } } private void drawRands(Graphics g, char[] rands) { // g.setColor(Color.BLUE); Random random = new Random(); int red = random.nextInt(110); int green = random.nextInt(50); int blue = random.nextInt(50); g.setColor(new Color(red, green, blue)); g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18)); g.drawString(\"\" + rands[0], 1, 17); g.drawString(\"\" + rands[1], 16, 15); g.drawString(\"\" + rands[2], 31, 18); g.drawString(\"\" + rands[3], 46, 16); } private char[] generateCheckCode() { String chars = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; char[] rands = new char[4]; for (int i = 0; i < 4; i++) { int rand = (int) (Math.random() * 36); rands[i] = chars.charAt(rand); } return rands; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } } OK!!!保存为RandomCode.java吧,然后进行编译,生成RandomCode.class文件,放到WEB-INF/classes/org/yuanliang目录下; 然后在WEB-INF目录下建立web.xml,添加Servlet配置: jsp验证码生成以及刷新 关于jsp验证码生成,显示,验证和刷新: 1:四位数据的验证图片生成,用servlet实现 2: 在web.xmlli配置servlet 3:页面上显示servlet生成的图片 4: 关于验证码输入数据的验证 5: 验证码的刷新 ——————————————————————– 1:四位数据的验证图片生成,用servlet实现,servlet代码如下: import java.io.*; import javax.servlet.http.*; import javax.servlet.*; import java.util.*; import java.awt.*; import java.awt.image.*; import javax.imageio.*; public class vImage extends HttpServlet { public void init(ServletConfig conf) throws ServletException { super.init(conf); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType(”image/jpeg”); res.setHeader(”Pragma”, “No-cache”); res.setHeader(”Cache-Control”, “no-cache”); res.setDateHeader(”Expires”, 0); HttpSession session = req.getSession(); // 在内存中创建图象 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)); // 画边框 //g.setColor(new Color()); //g.drawRect(0,0,width-1,height-1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(getRandColor(160, 200)); for (int i = 0; i 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); } } 2: 在web.xmlli配置servlet: vImage /vimage 注:注意元素在web.xml文件里的位置 3:页面上显示servlet生成的图片: 注:在需要显示验证码的地方加上这句,name在刷新验证码的时候会用到。 4: 关于验证码输入数据的验证: 验证码生成时存入了session,就是servlet里的这句session.setAttribute(”post_validate_code”, sRand);具体验证就不多说了。 5: 验证码的刷新 刷新验证码 function reloadImage(url) { document.form名字.pic.src = url; } 前两个有时间参考 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
展开全部
一个小示例看一下。。 验证码 code2.jsp <%@ page language="java" import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" pageEncoding="gb2312"%> <%try{ response.setHeader("Pragma","no-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires",0); response.setContentType("image/jpeg"); int width = 80; int height = 20; char mapTable[] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9'}; BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); // 设定背景颜色 g.setColor(new Color(0xDCDCDC)); 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 < 5; i++) { strEnsure += mapTable[(int) (mapTable.length * Math.random())]; } // 将验证码显示在图像中,如果要生成更多位的验证码,增加drawString语句 g.setColor(Color.red); g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18)); String str = strEnsure.substring(0, 1); g.drawString(str, 8, 17); 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, 50, 15); str = strEnsure.substring(4, 5); g.drawString(str, 65, 18); // 随机产生10个干扰点 Random random = new Random(); for (int i = 0; i < 10; i++) { int x = random.nextInt(width); int y = random.nextInt(height); g.drawOval(x, y, 1, 1); } // 释放图形上下文 g.dispose(); session.setAttribute("yanzhengma",strEnsure);//将验证码写入到session ImageIO.write(image, "JPEG", response.getOutputStream()); out.clear(); }catch(Exception e){ response.sendRedirect("log.jsp"); }%> 在log.jsp里 验证 <input type="text" name="confirm" id="confirm" style="width:100px; height:25px;"/> <img id="yzm" src=code2.jsp alt="看不清"/><a href="#" class="STYLE2" onclick="javascript:document.getElementById('yzm').src='code2.jsp';return false;">看不清,换一张</a>
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>无标题文档</title> //验证代码部分 <script language="JavaScript"> function abc() { if(form1.textfield.value=="") { window.alert("用户名不能为空!"); form1.textfield.focus(); //document.getElementById("textfield").focus(); return false; } else if(form1.textfield1.value=="") { window.alert("密码不能为空!"); form1.textfield1.focus(); return false; } } </script> </head> <body> <form name="form1" action="Default.aspx" method="get" > <table width="253" height="128" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="70">用户名:</td> <td width="183"><input type="text" id="textfield" value=""/></td> </tr> <tr> <td>密码:</td> <td><input type="password" id="textfield1" value=""/></td> </tr> <tr > <td colspan="2"> <input type="submit" value="提交" onclick="return abc()"/> <input type="reset" value="清空"/></td> </tr> </table> </form> </body> </html>
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询