doPost
private final int WIDTH = 150;
private final int HEIGHT = 30;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage bf = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) bf.getGraphics();//Graphics's son is powerful
graphics.setColor(Color.BLUE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
graphics.setColor(Color.red);
graphics.setFont(new Font("楷体",Font.BOLD,20));
Random random = new Random();
int m = 13;
for (int i = 0; i < 4; i++) {
int index = random.nextInt(base.length());
char charAt = base.charAt(index);
int jiaodu = random.nextInt(60)-30;
double theta = jiaodu*Math.PI/180;//弧度
graphics.rotate(theta, m, 19);
graphics.drawString(charAt+"", m, 15);
graphics.rotate(-theta, m, 19);
m+=20;
}
for (int i = 0; i < 4; i++) {
graphics.setColor(Color.white);
graphics.drawLine(random.nextInt(WIDTH),random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(HEIGHT));
}
ImageIO.write(bf, "png",response.getOutputStream());
}
login.html
<!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>Insert title here</title>
<script type="text/javascript">
function changeImage() {
document.getElementById("myimage").src="response/pic?" + new Date().getTime();
}
</script>
</head>
<body>
<form action="response/response_other" method="post">
<input type="text" name="username"><br/>
<input type="password" name="password"><br/>
<input type="text" name="checkcode"><br/>
<img src="response/pic" style="cursor: pointer;" onclick="changeImage();" id="myimage"><br>
<input type="submit" value="登录">
</form>
</body>
</html>