Java生成随机验证码图片,结果类似于:
其中login.html网页源码为:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>I lova Java</title>
</head>
<body>
<script type="text/javascript">
// 函数的{}一定不要忘了
function change() {
var imgObj = document.getElementById("img1");
imgObj.src="/07day/Index2?time=" + new Date().getTime();
//alert("" + new Date().getTime())
}
</script>
<form action="" method="post">
用户名:<input type="text" name="username"/><br/>
密码: <input type="password" name="password"/><br/>
<input type="text" size="5" name="code"/><img id="img1" src="/07day/Index2"/>
<a href="javascript:change()">看不清</a>
<input type="button" οnclick="change()" value="刷新"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
Java代码为:
package com.net;
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.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 输出随机图片
* Servlet implementation class Index2
*/
@WebServlet("/Index2")
public class Index2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Index2() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 120;
int height = 25;
// 创建内存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 得到画笔
Graphics g = image.getGraphics();
// 开始画
g.setColor(Color.BLUE);
g.drawRect(0, 0, width, height);
// 填充背景色
g.setColor(Color.YELLOW);
g.fillRect(1, 1, width - 2, height - 2);
// 画干扰线
g.setColor(Color.GRAY);
Random r = new Random();
for (int i = 0; i < 9; i++) {
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
// 验证码
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.ITALIC | Font.BOLD, 18));
int x = 20;
for (int i = 0; i < 4; i++) {
g.drawString(r.nextInt(10) + "", x, 20);
x += 20;
}
// 输出
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pramgra", "no-cache");
ImageIO.write(image, "jpg", response.getOutputStream());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}