网站登录经常会需要验证码,下面就是我实现的一个简单的验证码功能。
后台框架使用的是springMVC+spring+hibernate,前端页面使用的是html+freemarker。
1、验证码工具类
public class GetRandomCodeUtil {
public static byte[] getImage(String code){
int lengh=code.length();
int fsize=15;//字体大小
int fwidth=fsize+1;
int width=fwidth*lengh+6;//图片宽度
int height=fsize*2+1;//图片高度
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g=image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
//设置边框颜色
g.setColor(Color.LIGHT_GRAY);
//边框字体样式
g.setFont(new Font("Arial", Font.BOLD, height - 2));
//绘制边框
g.drawRect(0, 0, width - 1, height -1);
//绘制噪点
Random rand = new Random();
//设置噪点颜色
g.setColor(Color.LIGHT_GRAY);
for(int i = 0;i < lengh * 6;i++){
int x = rand.nextInt(width);
int y = rand.nextInt(height);
//绘制1*1大小的矩形
g.drawRect(x, y, 1, 1);
}
//绘制验证码
int codeY = height - 10;
//设置字体颜色和样式
g.setColor(new Color(19,148,246));
g.setFont(new Font("Georgia", Font.BOLD, fsize));
for(int i = 0; i < lengh;i++){
g.drawString(String.valueOf(code.charAt(i)), i * 16 + 5, codeY);
}
//关闭资源
g.dispose();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
byte[] bts=null;
try {
jpeg.encode(image);
bts = bos.toByteArray();
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bts;
}
public static String GetCode(int length){
char[] codes={'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z','A','B','C',
'D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V',
'W','X','Y','Z'};
int n=codes.length;
char[] result=new char[length];
for(int i=0;i<result.length;i++){
int r=(int) (Math.random()*n);
result[i]=codes[r];
}
return String.valueOf(result);
}
}
说明:主要通过java.awt包和Java随机数来实现将随机生成的验证码变成一个图片,工具类中可以自定义验证码数据库(见codes数组)。
二、控制层(cotroller)代码
@Controller("loginControl")
public class LoginControl {
@RequestMapping(value={"/code"},method=RequestMethod.GET)
public void code(HttpServletRequest req,HttpServletResponse res) throws IOException{
String imageCode=GetRandomCodeUtil.GetCode(4);
byte[] b=GetRandomCodeUtil.getImage(imageCode);
req.getSession().setAttribute("code", imageCode);
req.getSession().setMaxInactiveInterval(60000);
res.setContentType("image/jpeg");
res.setBufferSize(2048);
res.getOutputStream().write(b);
}
}
说明:调用工具类生成随机验证码,并存入session中,之后将验证码图片返回给前端页面。
三、前端页面代码(部分代码)
<#assign WEB_PATH = request.getContextPath()>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="${WEB_PATH}/css/login.css" type="text/css" charset="utf-8"/>
<script src="${WEB_PATH}/js/jquery.js" type="text/javascript"></script>
</head>
<body style="background:#3e6dbb;">
<div class="loginCon">
<div class="login">
<img src="${WEB_PATH}/images/loginLogo.png" alt="" width="701" height="125" />
<div class="area">
<form method="post" οnkeyup="keyUp(event)">
<!--
<p>
<label><input type="radio" name="userType" id="normal" value="0" checked="checked"/>超级管理员</label>
<label><input type="radio" name="userType" id="enterprise" value="1"/>业务管理员</label>
</p>
-->
<p>
<label><input type="hidden" name="userType" id="normal" value="0" /></label>
</p>
<p>用户名:<input type="text" name="name" id="name" class="inputW" /></p>
<p>密 码:<input type="password" name="password" id="pwd" class="inputW" /></p>
<p>验证码:<input type="text" name="code" id="code" class="inputW" />
<img alt="看不清 换一张" src="${WEB_PATH}/code" οnclick="refresh()" id="image"></img></p>
<p class="pBtn"><input type="button" value=" " class="inputBtn" οnclick="login()"/></p>
</form>
</div>
</div>
</div>
<script>
function refresh(){
$("#image").attr("src","${WEB_PATH}/code?timestamp="+new Date().getTime());
}
</script>
</body>
</html>
精彩科技工作室