java生成验证码

来源:互联网 发布:扑克牌记忆训练软件 编辑:程序博客网 时间:2024/06/06 23:35

(1)java代码部分

@RequestMapping("/drawCheckCode")public void drawCheckCode(HttpServletResponse resp,HttpSession session,Integer width,Integer height) throws IOException {resp.setContentType("image/jpg");if(width==null) width = 200;if(height==null) height = 100;int num = 5;//字符数String code = "0123456789abcdefg";Random ran = new Random();StringBuffer cc = new StringBuffer();for(int i=0;i<num;i++) {cc.append(code.charAt(ran.nextInt(code.length())));//随机生成字符串}<span style="white-space:pre"></span>//创建一个图片对象<span style="white-space:pre"></span>BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);<span style="white-space:pre"></span>Graphics2D graphic = img.createGraphics();//创建一个画笔,用来画内容<span style="white-space:pre"></span>graphic.setColor(Color.blue);//背景色(底色)是蓝色<span style="white-space:pre"></span>graphic.fillRect(20, 20, width, height);//画一个x=20,y=20,宽高的正方形图片<span style="white-space:pre"></span>graphic.setColor(Color.black);//边框颜色<span style="white-space:pre"></span>graphic.drawRect(0, 0, width-1, height-1);//加边框,黑色<span style="white-space:pre"></span>Font font = new Font("宋体",Font.BOLD+Font.ITALIC,(int)(height*0.8));<span style="white-space:pre"></span>graphic.setFont(font);//设置字体<span style="white-space:pre"></span>for(int i=0;i<num;i++) {<span style="white-space:pre"></span>graphic.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));//随机产生字体颜色<span style="white-space:pre"></span>graphic.drawString(String.valueOf(cc.charAt(i)), i*(width/num)+3,(int)(height*0.8));//一个一个画数字<span style="white-space:pre"></span>}<span style="white-space:pre"></span>//加一些点<span style="white-space:pre"></span>for(int i=0;i<(width+height);i++) {<span style="white-space:pre"></span>graphic.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));//随机产生字体颜色<span style="white-space:pre"></span>graphic.drawOval(ran.nextInt(width), ran.nextInt(height), 1, 1);//指的是在高度和宽度区域内随机画宽和高都为1px的点<span style="white-space:pre"></span>}<span style="white-space:pre"></span>//加一些线<span style="white-space:pre"></span>for(int i=0;i<4;i++) {<span style="white-space:pre"></span>graphic.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));//随机产生字体颜色<span style="white-space:pre"></span>graphic.drawLine(0, ran.nextInt(height), width,ran.nextInt(height));//画从点(0,随机)到点(width,随机)的线<span style="white-space:pre"></span>}<span style="white-space:pre"></span>graphic.drawString(cc.toString(), 0, height);<span style="white-space:pre"></span>OutputStream os = resp.getOutputStream();<span style="white-space:pre"></span>ImageIO.write(img, "jpg", os);//图片写出<span style="white-space:pre"></span>}

上面的实例,可以直接通过访问java代码来运行,最终生成的验证码类型如下图:


(2)可以封装成一个util,便于使用

①util类

public class Captcha {private int width;private int height;private int num;private String code;private static final Random ran = new Random();private static Captcha captcha;private Captcha(){code = "0123456789";num = 4;}public static Captcha getInstance() {if(captcha==null) captcha = new Captcha();return captcha;}public void set(int width,int height,int num,String code) {this.width = width;this.height = height;this.setNum(num);this.setCode(code);}public void set(int width,int height) {this.width = width;this.height = height;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String generateCheckcode() {StringBuffer cc = new StringBuffer();for(int i=0;i<num;i++) {cc.append(code.charAt(ran.nextInt(code.length())));}return cc.toString();}public BufferedImage generateCheckImg(String checkcode) {//创建一个图片对象BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//获取图片对象的画笔Graphics2D graphic = img.createGraphics();graphic.setColor(Color.WHITE);graphic.fillRect(0, 0, width, height);graphic.setColor(Color.BLACK);graphic.drawRect(0, 0, width-1, height-1);Font font = new Font("宋体",Font.BOLD+Font.ITALIC,(int)(height*0.8));graphic.setFont(font);for(int i=0;i<num;i++) {graphic.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));graphic.drawString(String.valueOf(checkcode.charAt(i)), i*(width/num)+4, (int)(height*0.8));}//加一些点for(int i=0;i<(width+height);i++) {graphic.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));graphic.drawOval(ran.nextInt(width), ran.nextInt(height), 1, 1);}//加一些线for(int i=0;i<4;i++) {graphic.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));graphic.drawLine(0, ran.nextInt(height), width, ran.nextInt(height));}return img;}}
(2)action端调用,login.java

@RequestMapping("/drawCheckCode")public void drawCheckCode(HttpServletResponse resp,HttpSession session) throws IOException {resp.setContentType("image/jpg");width = 300;height = 100;Captcha c = Captcha.getInstance();c.set(width, height);String checkcode = c.generateCheckcode();
                session.setAttribute("cc",checkcode);OutputStream os = resp.getOutputStream();ImageIO.write(c.generateCheckImg(checkcode), "jpg", os);//图片写出}
@RequestMapping(value="/login",method=RequestMethod.GET)<span style="white-space:pre"></span>public String login(String username,String password,String checkcode,Model model,HttpSession session) {<span style="white-space:pre"></span>return "admin/login";<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>@RequestMapping(value="/login",method=RequestMethod.POST)<span style="white-space:pre"></span>public String login(String username,String password,String checkcode,Model model,HttpSession session) {<span style="white-space:pre"></span>String cc = (String)session.getAttribute("cc");<span style="white-space:pre"></span>if(!cc.equals(checkcode)) {<span style="white-space:pre"></span>model.addAttribute("error","验证码出错,请重新输入");<span style="white-space:pre"></span>return "admin/login";<span style="white-space:pre"></span>}<span style="white-space:pre"></span>User loginUser = UserService.login(username,password);<span style="white-space:pre"></span>session.setAttribute("loginUser", loginUser);<span style="white-space:pre"></span>return "redirect:/admin/";<span style="white-space:pre"></span><span style="white-space:pre"></span><span style="white-space:pre"></span>}
(3)前端

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/resources/css/admin/login.css"/><script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/jquery-1.7.2.min.js"></script><script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/jquery.validate.js"></script><script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/core/jquery.cms.validate.js"></script><script type="text/javascript">$(function(){$("#myForm").cmsvalidate();//判断用户名和密码是否正确});</script><title>后台管理登录</title><script type="text/javascript">function reCheckcode(img) {img.src="drawCheckCode?"+Math.random();//加随机数主要是为了消除缓存的影响}</script></head><body><div id="container"><div id="top"></div><div id="loginBar"><span id="showDate">请登录</span></div><div id="content"><div id="loginForm"><form method="post" id="myForm" action=""><table cellpadding="0" cellspacing="0" width="380px" id="loginTable"><tr><td align="right" width="90">登录用户:</td><td align="left"><input type="text" name="username" size="25"/> </td></tr><tr><td align="right">登录密码:</td><td align="left"><input type="password" name="password" size="25"/></td></tr><tr><td align="right">输入验证码:</td><td align="left"><input type="text" name="checkcode" id="validateCode" size="15"/>${error}</td></tr><tr><td align="left" colspan="2"><span style="margin-left:94px;cursor:pointer"><img src="drawCheckCode" onclick="reCheckcode(this)"/></span></td></tr><tr><td align="center" colspan="2"><input type="submit" value="登录">   <input type="reset" value="重置"/></td></tr></table></form></div></div></div></body></html>


②jquery处理前端验证

(function($){var __validate = $.fn.validate;$.fn.cmsvalidate = function(opts) {var __rules = $.extend({username:"required",password:"required",name:"required",confirmPwd:{equalTo:"#password"},email:"email"},opts?(opts.rules||{}):{});var __messages = $.extend({username:"用户名不能为空",password:"用户密码不能为空",confirmPwd:"两次输入的密码不正确",email:"邮件格式不正确",name:"名称不能为空"},opts?(opts.messages||{}):{});var __defaultOpts = $.extend(opts||{},{rules:__rules,messages:__messages,errorElement: opts?(opts.errorElement||"span"):"span",errorClass:opts?(opts.errorClass||"errorContainer"):"errorContainer"});$.extend($.fn.validate.prototype,__defaultOpts);__validate.call(this,__defaultOpts);}})(jQuery)








0 0
原创粉丝点击