欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java中生成图形验证码

程序员文章站 2024-03-23 10:13:58
...

java中生成图形验证码
点击图形验证码可以刷新验证码

1、首先创建一个生成验证码的工具类:RandomValidateCode

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 生成验证码
 */
public class RandomValidateCode {
	public static final String RANDOMCODEKEY = "randomcode_key";//放到session中的key
    private Random random = new Random();
    private String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
    
    private int width = 80;//图片宽
    private int height = 26;//图片高
    private int lineSize = 100;//干扰线数量
    private int stringNum = 4;//随机产生字符数量
    
    /**
     * 生成随机图片
     */
    public void getRandcode(HttpServletRequest request,HttpServletResponse response) {
        HttpSession session = request.getSession();
        //BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        //产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics g = image.getGraphics();
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
        g.setColor(getRandColor(160, 200));
        //绘制干扰线
        for(int i=0;i<=lineSize;i++){
            drowLine(g);
        }
        //绘制随机字符
        String randomString = "";
        for(int i=1;i<=stringNum;i++){
            randomString=drowString(g,randomString,i);
        }
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, randomString);
        g.dispose();
        try {
        	//将内存中的图片通过流动形式输出到客户端
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * 获得字体
     */
    private Font getFont(){
        return new Font("Fixedsys",Font.CENTER_BASELINE,18);
    }
    /*
     * 获得颜色
     */
    private Color getRandColor(int fc,int bc){
        if(fc > 255)
            fc = 255;
        if(bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc-fc-16);
        int g = fc + random.nextInt(bc-fc-14);
        int b = fc + random.nextInt(bc-fc-18);
        return new Color(r,g,b);
    }
    
    /*
     * 绘制字符串
     */
    private String drowString(Graphics g,String randomString,int i){
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
        randomString +=rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13*i, 16);
        return randomString;
    }
    /*
     * 绘制干扰线
     */
    private void drowLine(Graphics g){
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x+xl, y+yl);
    }
    /*
     * 获取随机的字符
     */
    public String getRandomString(int num){
        return String.valueOf(randString.charAt(num));
    }
}

html和css代码:

<html>
  <head>
    <title>登录</title>
	<meta name="decorator" content="default"/>
	<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<style>
		*{
			margin: 0 auto;
		}
		body{
			background-color: #343a40;
		}
		.container{
			position: relative;
			top: 100px;
		}
		.news-nav{
			clear: both;
			height: 80px;
			margin-left: 10px;
			margin-right: 10px;
			width: 300px;
			margin: 0 auto;
		}
		.news-nav li{
			float: left;
			list-style-type: none;
			margin: 0 10px;
			font-size: 30px;
			display: block;
			width: 86px;
			height: 79px;
			text-align: center;
			line-height: 79px;
			font-weight: bold;
			color: #007bff;
			cursor: pointer;
		}
		.modal-dialog{
			max-width: 100% !important;
		}
		.modal-content{
			background:rgba(0,0,0,0.3);
			width: 700px;
		}
		.loginForm{
			width: 400px;
		}
		.loginForm .form-group{
			margin: 30px 0;
		}
		.loginForm .form-group .form-control{
			height: 40px;
			font-size: 15px;
		}
		input[type="checkbox"]{
			position:relative;
			top:-2px;
			vertical-align: middle;
			cursor: pointer;
			zoom:1.6;
		}
		.btn-primary{
			background-color: #3e4963; 
			border: 0px solid transparent;
			width: 400px;
			height: 50px;
			font-size: 24px;
			font-family: STKaiti;
		}
		label{
			color: #fff;
			font-size: 16px;
		}
	</style>
  </head>
  <body>
	<div class="container">
		<div class="modal-dialog" id="login_form">
			<div class="modal-content">
				<div class="modal-title">
					 <ul class="news-nav js-nav-title">
						<li class="on" data="login">登录</li>
					 </ul>
				</div>
				<div class="modal-body index-news-list" id="index-news-list-1">
					<form class="loginForm" id="loginForm" action="" method="post">
						  <div class="form-group">
							  <input class="form-control required" name="name" id="name" type="text" placeholder="请输入用户名或邮箱">
						  </div>
						  <div class="form-group">
							  <input class="form-control required" name="password" id="password" type="password" placeholder="请输入密码">
						  </div>
						  <div class="form-group">
							<div class="row">
								<div class="col-sm-8">
									<input class="form-control required" name="vcode" id="vcode" type="text" placeholder="请输入验证码">
								</div>
								<div class="col-sm-4">
									<img src="/sys/user/getVcode" id="imgVerify" height="40" class="passcode" style="margin-left: -10px;cursor:pointer;">
								</div>
							</div>
			              </div>
						  <div class="form-group">
							  <label for="remember">
								<input type="checkbox" name="remember" id="remember" value="0"/> 记住我
							  </label>
						  </div>
						  <div class="form-group">
							  <button class="btn btn-primary" type="submit">登录</button>
						  </div>
					 </form>
				</div>
			</div>
		</div>
	</div>
	<script>
		//单击验证码图片时,刷新验证码
		$("#imgVerify").click(function() {
			$(this).attr("src","/sys/user/getVcode?"+Math.random());
		});
	</script>
  </body>
</html>

controller层代码:

@RequestMapping(value = "/sys/user")
public class UserController {
	/**
	 * 获取生成验证码显示到界面上
	 */
	@RequestMapping(value = {"getVcode"})
	public void getVcode(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		//设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        
        //设置响应头信息,告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

RandomValidateCode类可直接复制使用,html和controller中的代码将地址改成自己的就行

相关标签: java js