相信我们在许多地方都有看到过验证码,如登录或是注册,或者当你找回qq密码时。验证码俯拾皆是,也各有千秋,下面就来研究一下怎样使用验证码吧。
1.使用验证码的好处
验证码以不规则的形式存在于一个混合了许多干扰像素的图片,人眼看起来都费劲,机器识别起来就更困难。
它可以有效防止利用机器进行的批量注册、重复投票、灌水回帖、暴力**等恶意操作,对服务器的维护起到了至关重要的作用
2.怎样生成验证码
验证码的生成有好多种不同的方法,在我们学习javaweb的开发中一般使用servlet的方式生成验证码,这样做可以提高效率。
也使我们的开发变得简单多了,在源代码没有错误的情况下直接把他复制到eclipse项目下的src下面的包里。之后在配置一下web.xml
就可以了。验证码实际上也就是一幅图片,显示的时候只需使用<img src=""/>就可以显示了。对于切换验证码只需使用简单的javascript
就可以。另外验证码一般不区分大小写。因此判断的时候要注意。
下面是生成验证码的servlet
package servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ImageGenerator extends HttpServlet {
private static Color getRandColor(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);
}
private static String charsLong = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
private static String charsShort = "0123456789";
private static String chars = charsLong;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
int charsLength = chars.length();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 75, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, height));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 5; i++) { //这里把循环的次数修改为2可以使验证码变得清晰一些,以便查看。这边的循环次数也可以多一点
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sRand = new StringBuilder();
String[] fontNames = { "Times New Roman", "Arial", "Book antiqua",
"" };
for (int i = 0; i < 4; i++) {
g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC,
height));
char rand = chars.charAt(random.nextInt(charsLength));
sRand.append(rand);
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(String.valueOf(rand), 16 * i + random.nextInt(6)
+ 3, height - random.nextInt(4));
}
//把验证码存放在内置对象session中以便后面做判断
String yanzm=(String)sRand.toString();
HttpSession ses=request.getSession();
ses.setAttribute("yzm1",yanzm);
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 2; i++) { //这里把循环的次数修改为2可以使验证码变得清晰一些,以便查看。这边的循环次数也可以多一点
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(width);
int yl = random.nextInt(width);
g.drawLine(x, y, x + xl, y + yl);
}
g.dispose();
try {
Thread.sleep(100);
} catch (Exception ex) {
}
OutputStream os = response.getOutputStream();
ImageIO.write(image, "JPEG", os);
os.flush();
os.close();
} catch (Exception ex) {
}
}
}
3.修改一下web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>yzm</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- servlet是我的包名,包名由你们自己来定-->
<servlet>
<description></description>
<display-name>ImageGenerator</display-name>
<servlet-name>ImageGenerator</servlet-name>
<servlet-class>servlet.ImageGenerator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageGenerator</servlet-name>
<url-pattern>/yzm</url-pattern> <!-- 这里的映射路径可以随便写-->
</servlet-mapping>
<servlet>
<description></description>
<display-name>User</display-name>
<servlet-name>User</servlet-name>
<servlet-class>servlet.User</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>User</servlet-name>
<url-pattern>/hedui</url-pattern>
</servlet-mapping>
</web-app>
4.编写表单页引用验证码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
function checknumber(no) {
no.src="yzm?t="+new Date().getTime() ;
}
</script>
</head>
<body>
<form action="hedui" method="post">
用户名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"/><br/>
验证码:<input type="text" name="checknum"/>
<span><img alt="看不清请点击此处" src="yzm" onclick="checknumber(this)" style="cursor: pointer;"></span><br/>
<input type="submit" value="提交 "/>
<input type="reset" value="取消 "/>
</form>
</body>
</html>
5.进行简单的登录判断
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class User
*/
public class User extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String password=request.getParameter("password");
String checknum=request.getParameter("checknum");
HttpSession ses=request.getSession();
String yzm=(String)ses.getAttribute("yzm1"); //这里的yzm1就是上面记录的session
if("will".equals(name)&&"123".equals(password)&&yzm.equalsIgnoreCase(checknum)){
System.out.println("success");
}else{
System.out.println("fail");
}
}
}
还是老规矩,如果你在使用验证码时出现了问题可以联系我,我的QQ是1214273312,加我为好友时请注明“csdn网友”,我一般都在线。