1.jsp中编写
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>验证码</title> <script type="text/javascript"> function changeCode(){ var imgEle = document.getElementById("vimg"); /*时间的毫秒数*/ imgEle.src = "VerifyCodeServlet?t=" + Math.random(); } </script> </head> <body> <form action="VerifyCodeServlet" method="post"> <label>输入验证码</label><br/> <input type="text" name="randomCode"/><img id="vimg" title="点击更换" οnclick="changeCode();" src="VerifyCodeServlet"><br/> <input type="submit" value="登录" type="submit"> </form> </body> </html>
触发 VerifyCodeServlet产生验证码图片
package yanzhengma; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; 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; @SuppressWarnings("serial") public class VerifyCodeServlet extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=gb2312"; //设置字母的大小,大小 private Font mFont = new Font("Times New Roman", Font.PLAIN, 17); public void init() throws ServletException { super.init(); } 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); } public void service(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=100, height=18; 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(1, 1, width-1, height-1); g.setColor(new Color(102,102,102)); g.drawRect(0, 0, width-1, height-1); g.setFont(mFont); g.setColor(getRandColor(160,200)); //画随机线 for (int i=0;i<155;i++) { int x = random.nextInt(width - 1); int y = random.nextInt(height - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g.drawLine(x,y,x + xl,y + yl); } //从另一方向画随机线 for (int i = 0;i < 70;i++) { int x = random.nextInt(width - 1); int y = random.nextInt(height - 1); int xl = random.nextInt(12) + 1; int yl = random.nextInt(6) + 1; g.drawLine(x,y,x - xl,y - yl); } //生成随机数,并将随机数字转换为字母 String sRand=""; for (int i=0;i<6;i++) { int itmp = random.nextInt(26) + 65; char ctmp = (char)itmp; sRand += String.valueOf(ctmp); g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); g.drawString(String.valueOf(ctmp),15*i+10,16); } HttpSession session = request.getSession(true); session.setAttribute("rand",sRand); g.dispose(); ImageIO.write(image, "JPEG", response.getOutputStream()); } }
2.第二种验证码产生
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</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"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>登录</title> <style> body { margin: 0; padding: 0; } canvas { position: absolute; left:0px; top:0px; width: 100%; z-index:-1; } .login,.register { position: relative; top:50px; width:300px; margin: 0 auto; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 14px; color: #787878; border: 1px solid #CBCBCB; border-radius: 5px; box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.3); clear: both; z-index: 1000; background:#FFFFFF; } .animation-bounceIn { animation: bounceIn 600ms linear; -webkit-animation: bounceIn 600ms linear; -moz-animation: bounceIn 600ms linear; -o-animation: bounceIn 600ms linear; } /* 登录框动画 */ @keyframes bounceIn { 0% { opacity: 0; transform: scale(.3); } 50% { opacity: 1; transform: scale(1.05); } 70% { transform: scale(.9); } 100% { transform: scale(1); } } @-webkit-keyframes bounceIn { 0% { opacity: 0; -webkit-transform: scale(.3); } 50% { opacity: 1; -webkit-transform: scale(1.05); } 70% { -webkit-transform: scale(.9); } 100% { -webkit-transform: scale(1); } } @-moz-keyframes bounceIn { 0% { opacity: 0; -moz-transform: scale(.3); } 50% { opacity: 1; -moz-transform: scale(1.05); } 70% { -moz-transform: scale(.9); } 100% { -moz-transform: scale(1); } } @-o-keyframes bounceIn { 0% { opacity: 0; -o-transform: scale(.3); } 50% { opacity: 1; -o-transform: scale(1.05); } 70% { -o-transform: scale(.9); } 100% { -o-transform: scale(1); } } .header { position: relative; margin-bottom: 10px; padding: 25px 15px; text-align: center; cursor: default; word-wrap: break-word; font-size: 16px; line-height: 18px; font-weight: 700; } .content { border-top: 1px solid #EEE; margin: 0px; padding: 0px; } .input-wrap { position: relative; border-bottom: 1px solid #EEE; overflow: hidden; } .input-wrap input { margin: 0px; outline: 0px none; word-wrap: break-word; width: 100%; padding: 15px 10px; font-size: 14px; line-height: 1; border: 0px none; border-radius: 0px; box-shadow: none; box-sizing: border-box; color: #787878; background: #FFF; font-family: Arial,sans-serif; } .ico-show-password { position: absolute; top: 0px; right: 0px; margin: auto; width: 21px; height: 13px; border-style: solid; border-color: #FFF; border-width: 17px 8px 17px 0px; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAmCAMAAAAY0vCaAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAACHUExURUxpcc3NzdfX1+np6eDg4N3d3dnZ2f39//r7/NLS0gCE8PX19QJ74TeV5AJ/6O3t7QN42g1/3dXV1R2I4OPj453K7xKF5dvq+PHx8dTn9+Xw+vf3+Fyo6JDD7eXl5SmP406i54e+7X2667jX8+z0+/Pz86zS8sXe9Mzi9miv6USd5XKz6fxYih4AAAABdFJOUwBA5thmAAABeUlEQVQoFeVSCZKCQAyUYyYZkHM4FEEUFA/8//u2A1rl7hc2VWRmkqbTSWVDMCbaltZxHO0ZecM2+JhaP3B02ZfWBh4LTOJMqQ36FbhVSm8lIfjex508N9B7otR14SVe9j7AngocFSC/1ZLYUKoVKE1gU/Z9JcW0bRFX/iQPxyFqrZVypZcivnffeM/4pU8GRAue+lIJv3bBPzFNb37oUXoSPY7CkdqPnkV/iV9gkxLNb/0oiH5d6LXuV7/rfHqN+ahf81kY/rjNfzPpH/NrxlOW5fPxurzWfWDadVE2j8MrjvLBCEz2gelWZwOAuDZdGDfr/JmOSbwjroo8vhNf6hpe8MewM8xVEuVJ/gBnkdyF55KcQdkWya19hR32YVcUB8S7sGFDh6xAJIoJiSG8seBn4E0RVdfnNx785xZlF/7GUFPUqCL7DD0NUXXK5wdB80cP06WOxoPopwf0Q/On34P0+xqepyg/soQXHrnsxhjzOVff81kY/rgfOrQgZYcs0VYAAAAASUVORK5CYII="); background-position: 0px 0px; cursor: pointer; } .on { background-position: 0px -24px; } .off { background-position: 0px 0px; } .input-wrap .captcha-wrap { position: absolute; top: 0px; right: 10px; bottom: 0px; margin: auto; height: 30px; border-radius: 4px; overflow: hidden; cursor: pointer; } .input-wrap .captcha-wrap>img { height: 30px; width: 90px; } .footer { position: relative; margin: 20px 0px; height: 33px; } .footer .left { margin-left: 10px; color: #787878; height: 33px; line-height: 33px; float: left; } .footer .left a { color: #787878; text-decoration: none; outline: 0px none; } .footer .submit { border: 0px none; outline: 0px none; float: right; margin-right: 10px; color: #FFF; background: #0077D9; font-size: 14px; line-height: 1.7; text-decoration: none; vertical-align: middle; display: inline-block; text-align: center; padding: 4px 10px; cursor: pointer; border-radius: 3px; white-space: nowrap; box-sizing: border-box; } .register { display: none; } .go-login { padding-left: 5px; } </style> </head> <body> <div class="login animation-bounceIn"> <div class="header">Login</div> <form name="form" method="post" action="" > <div class="content"> <div class="input-wrap"> <input class="username" name="username" placeholder="学号" type="text" autofocus="autofocus"> </div> <div class="input-wrap"> <input class="password" name="password" placeholder="密码" type="password"> <div class="ico-show-password off"></div> </div> <div class="input-wrap"> <input class="captcha" name="captcha" placeholder="验证码" type="text"> <div class="captcha-wrap"> <img alt="验证码" id="img" src="/Test/VerifyCodeServlet" οnclick="change();" > </div> </div> </div> <div class="footer"> <div class="left"> <label class="remember_me"><input name="rememberme" value="y" type="checkbox" checked="checked"> 记住我</label> <span class="middot">·</span> <a class="go-reg" href="javascript:void(0);">没有帐号?</a> </div> <input class="submit" value="登录" type="submit"> </div> </form> </div> <div class="register"> <div class="header">register</div> <form name="form" method="post" action="" > <div class="content"> <div class="input-wrap"> <input class="no" name="no" placeholder="学号" type="text" autofocus="autofocus"> </div> <div class="input-wrap"> <input class="name" name="name" placeholder="姓名" type="text"> </div> <div class="input-wrap"> <input class="pwd" name="pwd" placeholder="密码" type="password"> <div class="ico-show-password off"></div> </div> <div class="input-wrap"> <input class="captcha" name="captcha" placeholder="验证码" type="text"> <div class="captcha-wrap"> <img alt="验证码" src="/Test/VerifyCodeServlet"> </div> </div> </div> <div class="footer"> <div class="left"> <a class="go-login" href="javascript:void(0);">已有账户 . 返回登录?</a> </div> <input class="submit " value="注册" type="submit" onClick="change()"> </div> </form> </div> <script src="assets/jquery.min-1.8.3.js"></script> <script src="assets/layer/layer.js"></script> <script> $(function(){ $(".ico-show-password").click(function() { var _this = $(this); _this.hasClass("off")?_this.removeClass("off").addClass("on"):_this.removeClass("on").addClass("off"); var _d = _this.siblings("input"); "password" === _d.prop("type") ? ( _d.prop("type", "text")) : ( _d.prop("type", "password")); }); $(".go-reg").click(function(){ $('.login').hide(); $('.register').show(); }); $(".go-login").click(function(){ $('.login').show(); $('.register').hide(); }); }); function change(){ var imgEle = document.getElementById("img"); /*时间的毫秒数*/ imgEle.src = "${pageContext.request.contextPath }/VerifyCodeServlet?a=" + new Date().getTime(); } </script> </body> </html>
产生验证码图片的代码VerifyCodeServlet
package xuex; import java.awt.image.BufferedImage; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.vcode.utils.VerifyCode; public class VerifyCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); VerifyCode vc = new VerifyCode(); BufferedImage image = vc.getImage();//获取一次性验证码图片 // 该方法必须在getImage()方法之后来调用 VerifyCode.output(image, response.getOutputStream());//把图片写到指定流中 // 把文本保存到session中,为LoginServlet验证做准备 request.getSession().setAttribute("vCode", vc.getText()); } }