这篇文章简单的写了一个java验证码,为之前写过的springMVC注册功能加上验证码,验证码的作用就不多说了,防止机器人程序恶意注册什么的。。。
基本的注册功能的实现请查看之前的文章Maven搭建springMVC+spring+hibernate实现用户注册
其中,我修改了该注册程序的部分代码,其中User.java,加上了password和code的属性,同时将password持久到数据库,code属性使用@transient注解使其不被持久到数据库。
User.java 中加上这两个属性,至于User的构造方法修改为public User(String id, Date regtime, String username,String password) 就不贴代码了。
[java]
private String password;
@Column(name="password",nullable=false,length=20)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String code;
@Transient //不需要持久到DB的属性使用该注解
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private String password;
@Column(name="password",nullable=false,length=20)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String code;
@Transient //不需要持久到DB的属性使用该注解
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}下面是验证码生成的controller,大部分代码都写上了注释。
CodeController.java
[java]
package com.sgl.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CodeController {
private int width = 90;//定义图片的width
private int height = 20;//定义图片的height
private int codeCount = 4;//定义图片上显示验证码的个数
private int xx = 15;
private int fontHeight = 18;
private int codeY = 16;
char[] codeSequence = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
@RequestMapping("/code")
public void getCode(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// 定义图像buffer
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// Graphics2D gd = buffImg.createGraphics();
//Graphics2D gd = (Graphics2D) buffImg.getGraphics();
Graphics gd = buffImg.getGraphics();
// 创建一个随机数生成器类
Random random = new Random();
// 将图像填充为白色
gd.setColor(Color.WHITE);
gd.fillRect(0, 0, width, height);
// 创建字体,字体的大小应该根据图片的高度来定。
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
// 设置字体。
gd.setFont(font);
// 画边框。
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
// 随机产生40条干扰线,使图象中的认证码不易被其它程序探测到。
gd.setColor(Color.BLACK);
for (int i = 0; i < 40; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);