package day06;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Response3 extends HttpServlet {
public static final int WIDTH = 120;
public static final int HEIGHT = 25;
private static final String Graphics2D = null;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
// 设置背景色
setBackGroup(g);
// 设置边框
setBorder(g);
// 划干扰线
drawRandomLine(g);
// 写随机数
drawRandmoNum(g);
// 图形写给浏览器
response.setContentType("image/jpeg");
ImageIO.write(image, "jpg", response.getOutputStream());
}
// 设置背景色
private void setBackGroup(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
// 设置边框
private void setBorder(Graphics g) {
g.setColor(Color.WHITE);
g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
}
// 划干扰线
private void drawRandomLine(Graphics g) {
g.setColor(Color.BLUE);
for (int i = 0; i < 4; i++) {
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(HEIGHT);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
// 写随机数
private void drawRandmoNum(Graphics g) {
g.setColor(Color.RED);
g.setFont(new Font("宋体",Font.BOLD,25));
String chs = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int x=10;
for (int i = 0; i < 4; i++) {
String numStr = chs.charAt(new Random().nextInt(chs.length())) + "";
g.drawString(numStr, x, 20);
x += 30;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
------------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title>register.html</title>
<script type="text/javascript">
function changeImage(img) {
img.src = img.src + "?" + new Date().getTime();
}
</script>
</head>
<body>
<form action="">
用户名:<input type="text" name="username"></br>
密码:<input type="text" name="password"></br>
认证码:<input type="text" name="checkcode">
<img src ="/servletdemo/servlet/Response3" οnclick="changeImage(this)" alt="换一张" style="CURSOR:pointer"></br>
<input type="submit" value="注册">
</form>
</body>
</html>