1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 <script type="text/javascript"> 6 function _change() { 7 var imgEle = document.getElementById("image"); 8 imgEle.src = "/VerifyCodeServlet?a="+new Date().getTime(); 9 10 } 11 </script> 12 </head> 13 <body> 14 <%--本页面提供登录表单,还要显示错误信息--%> 15 <h1>登录</h1> 16 <% 17 /* 18 读取名为uname的cookie. 19 如果为空显示:"" 20 如果不为空显示:Cookie的值 21 */ 22 String uname = ""; 23 Cookie[] cs = request.getCookies();//获取请求中所有的cookie 24 if(cs != null) { //如果存在cookies 25 for(Cookie c : cs) { //循环遍历所有的cookie 26 if("uname".equals(c.getName())){ //查找名为uname的cookie 27 uname = c.getValue();//获取这个cookie的值,给uname这个变量 28 } 29 } 30 } 31 %> 32 <% 33 String message = ""; 34 String msg = (String) request.getAttribute("msg");//获取request域中的名为msg的属性 35 if (msg!=null) { 36 message = msg; 37 } 38 %> 39 40 <font color="red"><b><%=message %></b></font> 41 <form action="/LoginServlet" method="post"> 42 <%-- 把cookie中的用户名显示到用户文本框中 --%> 43 <table border="0"> 44 <tr> 45 <td>用户名:</td> 46 <td><input type="text" name="username" value="<%=uname %>"size="15"/></td> 47 </tr> 48 <tr> 49 <td>密 码:</td> 50 <td><input type="password" name="password" size="15"/> 51 </td> 52 </tr> 53 <tr> 54 <td>验证码:</td> 55 <td><input type="text" name="verifyCode" size="6"/><img id="image" src="/VerifyCodeServlet"> 56 <a href="javascript:_change()">换一张</a> 57 </td> 58 </tr> 59 </table> 60 <br/> 61 <input type="submit" value="登录" style="color: black"> 62 </form> 63 </body> 64 </html>
1 @WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet") 2 public class LoginServlet extends HttpServlet { 3 protected void doPost(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 /* 6 *校验验证码 7 * 1、从session中获取周期的验证码 8 * 2、从表单中获取用户填写的验证码 9 * 3、进行比较 10 * 4、如果相同,向下执行,否则保存错误信息到request域,转发到login.jsp 11 * */ 12 String sessionCode = (String) request.getSession().getAttribute("session_vcode"); 13 String paramCode = request.getParameter("verifyCode"); 14 if (!paramCode.equalsIgnoreCase(sessionCode)) { 15 request.setAttribute("msg","验证码错误!"); 16 request.getRequestDispatcher("/jsps/login.jsp").forward(request,response); 17 return; 18 } 19 20 /* 21 * 1、获取表单数据 22 * */ 23 request.setCharacterEncoding("utf-8"); 24 //获取 25 String username = request.getParameter("username"); 26 String password = request.getParameter("password"); 27 /* 28 * 2、校验用户名和密码是否正确 29 * */ 30 if (!"itcast".equalsIgnoreCase(username)) { //登录成功 31 /* 32 * 附加项:把用户名保存到cookie中,发送给客户端浏览器 33 * 当再次打开login.jsp时,login.jsp中会读取request中的cookie,把它显示到用户名文本框中 34 * */ 35 Cookie cookie = new Cookie("uname",username);//创建cookie 36 cookie.setMaxAge(60*60*24);//设置cookie命长为1天 37 response.addCookie(cookie); 38 /* 39 * 3、如果成功 40 * 保存用户信息到session中 41 * 重定向到succ1.jsp 42 * */ 43 HttpSession session = request.getSession();//获取session 44 session.setAttribute("username",username);//向session域中保存用户名 45 response.sendRedirect("/jsps/succ1.jsp"); 46 }else { //登录失败 47 /* 48 * 4、如果失败 49 * 保存错误信息到request域中 50 * 转发到login.jsp 51 * */ 52 request.setAttribute("msg","用户或密码错误"); 53 RequestDispatcher qr = request.getRequestDispatcher("/jsps/login.jsp");//得到转发器 54 qr.forward(request,response);//转发 55 } 56 } 57 58 protected void doGet(HttpServletRequest request, HttpServletResponse response) 59 throws ServletException, IOException { 60 doPost(request,response); 61 } 62 }
1 @WebServlet(name = "VerifyCodeServlet",urlPatterns = "/VerifyCodeServlet") 2 public class VerifyCodeServlet extends HttpServlet { 3 protected void doGet(HttpServletRequest request, HttpServletResponse response) 4 throws ServletException, IOException { 5 /* 6 * 1、保存图片 7 * 2、保存图片上的文本到session域中 8 * 3、把图片响应给客户端 9 * */ 10 VerifyCode vc = new VerifyCode(); 11 BufferedImage image = vc.getImage(); 12 request.getSession().setAttribute("session_vcode",vc.getText());//保存图片上的文本到session域中 13 14 try { 15 VerifyCode.output(image,response.getOutputStream()); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } 19 } 20 }
1 /* 2 * 验证码图片生成方法 3 * */ 4 public class VerifyCode { 5 private int w = 70; 6 private int h = 35; 7 private Random r = new Random(); 8 //可选的字体 9 private String[] fontNames = {"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312"}; 10 //可选的字符 11 private String codes = "23456789abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYX"; 12 private Color bgColor = new Color(255,255,255); 13 private String text; 14 15 //生成随机的颜色 16 private Color randomColor() { 17 int red = r.nextInt(150); 18 int green = r.nextInt(150); 19 int blue = r.nextInt(150); 20 return new Color(red,green,blue); 21 } 22 23 //生成随机字体 24 private Font randomFont() { 25 int index = r.nextInt(fontNames.length); 26 String fontName = fontNames[index];//生成随机的字体名称 27 int style = r.nextInt(4);//生成随机的样式,0(无样式),1(粗体),2(斜体),3(粗体加斜体) 28 int size = r.nextInt(5)+25;//生成随机字号24-28 29 return new Font(fontName,style,size); 30 } 31 32 //画干扰线 33 private void drawLine(BufferedImage image) { 34 int num = r.nextInt(6); 35 Graphics2D g2 = (Graphics2D)image.getGraphics(); 36 for (int i = 0; i < num; i++) {//生成两个点的坐标,即4个值 37 int x1 = r.nextInt(w); 38 int y1 = r.nextInt(h); 39 int x2 = r.nextInt(w); 40 int y2 = r.nextInt(h); 41 g2.setStroke(new BasicStroke(1.5F)); 42 g2.setColor(Color.BLUE);//干扰线是蓝色 43 g2.drawLine(x1,y1,x2,y2);//画线 44 } 45 } 46 47 //生成随机一个字符 48 private char randomChar() { 49 int index = r.nextInt(codes.length()); 50 return codes.charAt(index); 51 } 52 53 //创建一个BufferedImage 54 private BufferedImage creatImage() { 55 BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB); 56 Graphics2D g2 = (Graphics2D) image.getGraphics(); 57 g2.setColor(this.bgColor); 58 g2.fillRect(0,0,w,h); 59 return image; 60 } 61 62 //调用这个方法得到验证码 63 public BufferedImage getImage() { 64 BufferedImage image = creatImage(); //创建图片缓冲区 65 Graphics2D g2 = (Graphics2D) image.getGraphics();//得到绘制环境 66 StringBuilder sb = new StringBuilder();//用来装载生成的验证码文本 67 for (int i = 0; i <4 ; i++) {//循环四次,每次随机生成一个字符 68 String s = randomChar()+"";//随机生成一个字符 69 sb.append(s);//把字母添加到sb中 70 float x = i * 1.0F * w / 4;//设置当前字符的x轴坐标 71 g2.setFont(randomFont());//设置随机字体 72 g2.setColor(randomColor());//设置随机颜色 73 g2.drawString(s,x,h-5);//画图 74 } 75 this.text = sb.toString();//把生成的字符串赋给了this.text 76 drawLine(image);//添加干扰线 77 return image; 78 } 79 //返回验证码图片上的文本 80 public String getText() { 81 return text; 82 } 83 //保存图片到指定的输出流 84 public static void output (BufferedImage image, OutputStream out) 85 throws Exception{ 86 ImageIO.write(image,"JPEG",out); 87 } 88 }
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 <h1>succ1</h1> 8 <% 9 String username = (String)session.getAttribute("username"); 10 if(username == null) { 11 request.setAttribute("msg","您还没有注册"); 12 request.getRequestDispatcher("/jsps/login.jsp").forward(request,response); 13 return; 14 } 15 %> 16 欢迎<%=username %> 17 </body> 18 </html>