1.生成验证码大概有三种方式一是用servlet ,二是开源组件(Jcaptcha),Kaptcha.
2.用servlet实现
验证码包括输入框,和验证码图片
验证码图片的生成:
制作页面
ImageServlet
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Color c = new Color(200,150,255);
g.setColor(c);
g.fillRect(0, 0, 68, 22);
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random r = new Random();
int len=ch.length,index;
StringBuffer sb = new StringBuffer();
for(int i=0; i<4; i++){
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
g.drawString(ch[index]+"", (i*15)+3, 18);
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());
}
}
LoginServlet
public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
String piccode = (String) request.getSession().getAttribute("piccode");
String checkcode = request.getParameter("checkcode");
checkcode = checkcode.toUpperCase();
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
if(checkcode.equals(piccode)){
out.println("验证码输入正确!");
}else{
out.println("验证码输入错误!!!");
}
out.flush();
out.close();
}
}
页面
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function reloadCode(){
var time = new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/ImageServlet?d="+time;
}
</script>
</head>
<body>
<form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="get">
验证码:<input type="text" name="checkcode"/>
<img alt="验证码" id="imagecode" src="<%=request.getContextPath() %>/servlet/ImageServlet"/>
<a href="javascript: reloadCode();">看不清楚</a><br>
<input type="submit" value="提交">
</form>
</body>
</html>
2.利用开源插件生成验证码
http://user.qzone.qq.com/2223597272/blog/1467457239