Java Servlet 生成动态图片验证码Demo


一个简单的Java Servlet生成动态图片验证码的Demo,没有使用额外的外部包。

Index.jsp运行效果:

Java Servlet 生成动态图片验证码

  • 自定义图片大小
  • 自定义随机字符(数字,大小写字母)
  • 自定义前景色和背景色
  • 自定义干扰点数量

GetKey.java:最重要的一个工具类,生成图片验证码。
[java]
package net.singlex.img;
/**
* 工具类,生成图片验证码
*/

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("serial")
public class GetKey extends HttpServlet {

public static final char[] CHARS = { ‘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’ };

static Random random = new Random();

public String getRandomStr() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 6; i++) {// 生成6个字符
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
return buffer.toString();
}

// 取随机颜色
public static Color getRandomColor() {
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}

// 取随机颜色的反色
public static Color getReverseColor(Color c) {
return new Color(255 – c.getRed(), 255 – c.getGreen(), 255 – c.getBlue());
}

/**
* Constructor of the object.
*/
public GetKey() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
String randStr = getRandomStr();
request.getSession(true).setAttribute("randStr", randStr);
System.out.println("code:"+randStr);
// 设置图片的宽高
int width = 100;
int height = 30;
Color bColor = getRandomColor();// 背景色
Color fColor = getReverseColor(getRandomColor());// 前景色
// 创建一个彩色图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//
Graphics2D g = image.createGraphics();
g.setFont(new Font("宋体", Font.BOLD, 20));
// 先画背景色
g.setColor(bColor);
g.fillRect(0, 0, width, height);
// 画前景色
g.setColor(fColor);
g.drawString(randStr, 20, 22);
// 画出干扰点
for (int i = 0, n = random.nextInt(100); i < n; i++) {
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
ServletOutputStream outStream = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
encoder.encode(image);
outStream.flush();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");

out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}
[/java]

LoginServlet.java:登录验证模块
[java]
package net.singlex.img;

/**
* 登录验证模块
*/

import java.io.IOException;
import java.io.PrintWriter;

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 LoginServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public LoginServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//获取用户输入
String name= request.getParameter("name");
String password = request.getParameter("password");
String imgcodeStr = request.getParameter("checkkey");

//获取后台用户信息和验证码
HttpSession session = request.getSession();
String randCode = (String)session.getAttribute("randStr");

//匹配
if(name!=null && password!=null && imgcodeStr != null){
if(name.equals("admin") && password.equals("admin") && imgcodeStr.equalsIgnoreCase(randCode)){
System.out.println("登录成功……");
}else{
System.out.println("登录失败……");
}
}
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

this.doGet(request, response);
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}
[/java]

index.jsp:网页部分,关键是js脚本
[java]
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="net.singlex.img.GetKey" %>
<jsp:useBean id="show" scope="page" class="net.singlex.img.GetKey" />
<%
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 changeImg(){
document.getElementById("ch").disabled=true;
document.getElementById("imc").src="GetKey.jpeg?timestamp=" + new Date().getTime();
}
</script>
</head>

<body>
<form action="LoginServlet" method="get">
<table>
<tr><td colspan="4" align="center">后台登陆</td></tr>
<tr>
<td>账号</td><td colspan="3"><input type="text" name="name" /></td>
</tr>
<tr>
<td>密码</td><td colspan="3"><input type="password" name="password" /></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" name="checkkey" /></td>
</tr>
<tr>
<td><img src="GetKey.jpeg" id="imc" onload="ch.disabled=false" /></td>
<td><a href="javascript:onclick=changeImg()" id="ch">看不清,换一张</a></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
[/java]

ProjectDemo:百度网盘下载

发表评论