验证码的验证需要三个类
public class ImgFontByte {
public Font getFont(int fontHeight){
try {
Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(hex2byte(getFontByteStr())));
return baseFont.deriveFont(Font.PLAIN, fontHeight);
} catch (Exception e) {
return new Font("Arial",Font.PLAIN, fontHeight);
}
}
private byte[] hex2byte(String str) {
if (str == null)
return null;
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1)
return null;
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer
.decode("0x" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}
public class ValidateCode {
// 宽
private int width = 160;
// 高
private int height = 40;
// 字符数
private int codeCount = 5;
// 干扰线条数
private int lineCount = 150;
// 验证码
private String code = null;
// 图片
private BufferedImage buffImg=null;
private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UserServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Object vCode = session.getAttribute("code");
String code = request.getParameter("vCode");
//验证码是否正确s
if(code.equalsIgnoreCase((String)vCode)) {
//移除
session.removeAttribute("code");
String name = request.getParameter("name");
String age = request.getParameter("age");
//处理业务
System.out.println(name+":"+age);
request.setAttribute("msg", "处理成功");
request.getRequestDispatcher("/info.jsp").forward(request, response);
}else {
request.setAttribute("msg", "验证码不正确");
request.getRequestDispatcher("/info.jsp").forward(request, response);
}
}