最近给某气象局开发的系统中,客户要求加上验证码功能,验证码最主要的功能是防止恶意程序进行批量操作,其实内部应用系统自我感觉是没有必要有验证码的,但是为了显现我们是大公司,不是小作坊,还是加上吧,废话不多说,直接上代码;
一、创建生成随机数的工具类RandomUtil
package com.metarnet.util;
import java.awt.Color;
import java.util.Random;
/**
* 各种随机数工具类
*
* @author
*/
public class RandomUtil {
private char getRandomAlphabet() {
String word = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Double n = Math.random() * word.length();
return word.charAt(n.intValue());
}
private char getRandomLowerAlphabet() {
String word = "abcdefghijklmopqrstuvwxyz";
Double n = Math.random() * word.length();
return word.charAt(n.intValue());
}
private char getRandomUpperAlphabet() {
String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Double n = Math.random() * word.length();
return word.charAt(n.intValue());
}
private String getRandomNumber() {
Random random = new Random();
return String.valueOf(random.nextInt(10));
}
private char getRandomAlphabetAndNumber() {
String word = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Double n = Math.random() * word.length();
return word.charAt(n.intValue());
}
public Color getRandomColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**
* 生成随机字符
*
* @param len
* 字符的长度
* @param point
* 指示器: 0表示生成小写字母, 1表示生成大写字母, 2表示生成大小写字母, 3表示生成数字, 4表示生成大小写字母和数字
* @return 生成的字符串
*/
public String getRandomWord(int len, int point) {
if (len <= 0)
return null;
StringBuffer str = new StringBuffer();
for (int i = 0; i < len; i++) {
if (point == 0)
str.append(getRandomLowerAlphabet());
else if (point == 1)
str.append(getRandomUpperAlphabet());
else if (point == 2)
str.append(getRandomAlphabet());
else if (point == 3)
str.append(getRandomNumber());
else if (point == 4)
str.append(getRandomAlphabetAndNumber());
else
return null;
}
return str.toString();
}
public static void main(String[] args) {
RandomUtil util = new RandomUtil();
System.out.println(util.getRandomWord(4, 4));
}
}
二,创建生成验证码的JSP文件,checknum.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page language="java" contentType="image/jpg" errorPage="" %>
<%@ page import="java.awt.*, java.awt.image.*, java.util.*, javax.imageio.*" %>
<%@ page import="com.metarnet.util.RandomUtil" %>
<%!
RandomUtil util = new RandomUtil();
%>
<%
//验证码
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(util.getRandomColor(201, 255));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.BOLD, 18));
g.setColor(util.getRandomColor(160, 200));
for(int i=0; i<155; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x, y, x+x1, y+y1);
}
int len = 4;
String word = util.getRandomWord(len, 4);
g.setColor(new Color(20+random.nextInt(110), 20+random.nextInt(110), 20+random.nextInt(110)));
g.drawString(word, 8, 16);
session.setAttribute("checknum", word);
g.dispose();
ImageIO.write(image, "JPG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
三,创建登陆测试文件,login.jsp
<!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">
<title>验证码测试</title>
<script type="text/javascript" charset="utf-8">
//重新加载验证码
function reChangeImgSrc(){
$("#checknumimg").attr("src", "checknum.jsp");
var imgSrc = $("#checknumimg");
var src = imgSrc.attr("src");
imgSrc.attr("src",chgUrl(src));
$('#fmsg').html('');
$('#checknum').val('');
}
//时间戳
//为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
function chgUrl(url){
var timestamp = (new Date()).valueOf();
url = url.substring(0,17);
if((url.indexOf("&")>=0)){
url = url + "×tamp=" + timestamp;
}else{
url = url + "?timestamp=" + timestamp;
}
return url;
}
</script>
</head>
<body>
<img src="checknum.jsp" id="checknumimg" width="60" height="20" οnclick="reChangeImgSrc();"/>
<a href="javascript:void(0);" οnclick="reChangeImgSrc();">看不清楚,换一张</a>
</body>
</html>
四,效果图