1.生成验证页面
<%@ page language="java" import="java.util.*,java.awt.*" contentType="image/jpeg"%> <%@ page import="java.awt.image.*"%> <%@ page import="java.awt.Graphics,javax.imageio.*"%> <%! 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); } %> <% response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires",0); //在内存中创建图像 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(getRandColor(160,200)); for(int i=0;i<155;i++){ int x= random.nextInt(width); int y = random.nextInt(height); int x1 = random.nextInt(12); int y1 = random.nextInt(12); g.drawLine(x,y,x1,y1); } //随机产生的认证码(4位数) String sRand = ""; for(int i=0;i<4;i++){ String rand = String.valueOf(random.nextInt(10)); sRand +=rand; g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); g.drawString(rand,13*i+6,16); } //将认证码存放在session中 session.setAttribute("rand",sRand); //图像生效 g.dispose(); //输出图像到页面 ImageIO.write(image,"JPEG",response.getOutputStream()); out.clear(); out = pageContext.pushBody(); %>
2.用户登录页面,调用生成验证码页面
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'login.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"> <link rel="stylesheet" type="text/css" href="../css/login.css"> <script type="text/javascript"> function checkForm(){ if(checkUsername() && checkPass() && checkCode()){ return true; } return false; } function checkUsername(){ var name = document.getElementById("username").value; var namePattern=/^[a-zA-Z0-9]\w{0,15}$/; if(name.length == 0){ alert("用户名不能为空!"); return false; } if(!namePattern.test(name)) { alert("用户名输入出错!"); return false; } return true; } function checkPass(){ var pass = document.getElementById("password").value; var pushMoneyPattern=/^[a-zA-Z0-9]\w{0,15}$/; //表示只能是数字 if(pass.length == 0){ alert("密码不能为空!"); return false; } if(!pushMoneyPattern.test(pass)){ alert("密码输入错误!"); return false; } return true; } function checkCode(){ var code = document.getElementById("txtCheckCode").value; var codePattern = /^[0-9]{4}$/; if(code.length == 0){ alert("验证码不能为空!"); return false; } if(!codePattern.test(code)){ alert("验证码只能是四位数字! "); return false; } return true; } function loadimage(){ document.getElementById("randImage").src = "checkCode.jsp?"+Math.random(); } </script> </head> <body> <form action="/Chapter06/BankLoginServlet" method="post" onsubmit="return checkForm()"> <table cellpadding="0" cellspacing="0" border="1px solid black" width="320px" height="120px"> <tr> <td class="loginTitle">用户名:</td> <td class="loginValue"><input type="text" name="username" /></td> </tr> <tr> <td class="loginTitle">密 码:</td> <td class="loginValue"><input type="password" name="password" size="21" /></td> </tr> <tr> <td class="loginTitle">验证码:</td> <td class="loginValue" nowrap> <input type="text" name="txtCheckCode" id="txtCheckCode"> <img src="checkCode.jsp" name="randImage" id="randImage" alt="看不清换一张" onclick="javascript:loadimage();" /> </td> </tr> <tr> <td id="btn" colspan="2"> <input type="submit" value="提交" /> <input type="reset" value="重置" /> </td> </tr> </table> </form> </body> </html>
3.验证用户登录的servlet
package com.chapter06.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chapter06.bo.UserBo; import com.chapter06.bo.impl.UserBoImpl; public class BankLoginServlet extends HttpServlet { /* * 对输入的用户名、密码和验证码进行验证 * */ private UserBo userBo; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { userBo = new UserBoImpl(); response.setContentType("text/html;charset=gbk"); PrintWriter out = response.getWriter(); //获取表单中的数据 String username = request.getParameter("username"); String password = request.getParameter("password"); String checkCode = request.getParameter("txtCheckCode"); System.out.println(username); System.out.println(password); System.out.println(checkCode); //获取在session域中随机产生的验证码 String randCode = request.getSession().getAttribute("rand").toString(); System.out.println(randCode); //首先对验证码进行判断 if(!checkCode.equals(randCode)){ out.print("<script>alert('验证码输入错误!');location.href='bankLogin/login.jsp';</script>"); }else{ if(userBo.validUserByNameAndPwd(username, password)){ request.setAttribute("username", username); request.getRequestDispatcher("bankLogin/index.jsp").forward(request, response); }else{ out.print("<script>alert('用户名或密码验证错误!');location.href='bankLogin/login.jsp';</script>"); } } } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }