验证码功能——(四)
1.验证码插件JSP:
生成验证码并将生成的验证码存入session中。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Random"%> <%@ page import="java.io.OutputStream"%> <%@ page import="java.awt.Color"%> <%@ page import="java.awt.Font"%> <%@ page import="java.awt.Graphics"%> <%@ page import="java.awt.image.BufferedImage"%> <%@ page import="javax.imageio.ImageIO"%> <% int width = 60; int height = 32; //create the image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // set the background color g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, width, height); // draw the border g.setColor(Color.black); g.drawRect(0, 0, width - 1, height - 1); // create a random instance to generate the codes Random rdm = new Random(); String hash1 = Integer.toHexString(rdm.nextInt()); System.out.print(hash1); // make some confusion for (int i = 0; i < 50; i++) { int x = rdm.nextInt(width); int y = rdm.nextInt(height); g.drawOval(x, y, 0, 0); } // generate a random code String capstr = hash1.substring(0, 4); //将生成的验证码存入session session.setAttribute("validateCode", capstr); g.setColor(new Color(0, 100, 0)); g.setFont(new Font("Candara", Font.BOLD, 24)); g.drawString(capstr, 8, 24); g.dispose(); //输出图片 response.setContentType("image/jpeg"); out.clear(); out = pageContext.pushBody(); OutputStream strm = response.getOutputStream(); ImageIO.write(image, "jpeg", strm); strm.close(); %>
2.登录界面请求验证码URL
<TR> <TD>验证码:</TD> <TD><input id="randomcode" name="randomcode" size="8" /> <img id="randomcode_img" src="${baseurl}validatecode.jsp" alt="" width="56" height="20" align='absMiddle' /> <a href=javascript:randomcode_refresh()>刷新</a></TD> </TR>
3.控制层验证验证码的正确性
从session中取出验证码进行验证
@RequestMapping("/login") public String login(HttpSession session, String randomcode,String usercode,String password)throws Exception{ //校验验证码,防止恶性攻击 //从session获取正确验证码 String validateCode = (String) session.getAttribute("validateCode"); //输入的验证和session中的验证进行对比 if(!randomcode.equals(validateCode)){ //抛出异常 throw new MyException("验证码输入错误"); } //调用service校验用户账号和密码的正确性 ActiveUser activeUser = sysService.authenticat(usercode, password); //如果service校验通过,将用户身份记录到session session.setAttribute("activeUser", activeUser); //重定向到商品查询页面 return "redirect:/first.action"; }
【当你用心写完每一篇博客之后,你会发现它比你用代码实现功能更有成就感!】