public class ValidateCodeService { static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static Random rnd = new Random(); public static String createRandomString(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append(AB.charAt(rnd.nextInt(AB.length()))); return sb.toString(); } public static Image getImage(String code) { BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, 80, 30); g.setColor(Color.BLACK); g.setFont(new Font(null, Font.BOLD, 20)); g.drawString(code, 0, 20); return image; } }
Output servlet
URL: /ValidateCode
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setDateHeader("Expires", -1); response.setHeader("Cache-Control","no-cache"); response.setHeader("Pragma","no-cache"); response.setHeader("Content-Type", "image/jped"); String code = ValidateCodeService.createRandomString(4); request.getSession().setAttribute("ValidateCode", code); Image image = ValidateCodeService.getImage(code); ImageIO.write((RenderedImage) image, "jpg", response.getOutputStream()); }
View
out.println( "Validation Code: <input type='text' name='ValidateCode'/>" +"<img id='ValidateCodeImg' src='"+request.getContextPath()+"/ValidateCode'>" +"<a href='#' rel='nofollow' title='Refresh Image' onclick=\"document.getElementById('ValidateCodeImg').src = '"+request.getContextPath()+"/ValidateCode?'+Date.now();return false;\">" +"Refresh" +"</a>" +"<br>");
No comments:
Post a Comment