javaweb中使用servlet实现验证码
package com.test;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/che")
public class che extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int w =120;
int h =60;
BufferedImage img = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics();
g.setColor(Color.PINK);
g.fillRect(0,0,w,h);
g.setColor(Color.blue);
g.drawRect(0,0,w-1,h-1);
String str ="abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRZTUVWXYZ";
Random r = new Random();
StringBuffer s = new StringBuffer();
for(int i=0 ;i<4;i++) {
int n = r.nextInt(str.length());
String ss = str.substring(n,n+1);
s.append(ss);
g.drawString(ss,20*(i+1),15);
}
g.setColor(Color.GREEN);
g.drawLine(5,25,100,30);
g.setColor(Color.RED);
g.drawLine(2,7,110,45);
g.setColor(Color.YELLOW);
g.drawLine(0,58,115,0);
g.setColor(Color.BLACK);
g.drawLine(50,0,50,60);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(img,"jpg",out);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request ,response);
}
}
``
## //html代码
1,输出验证码
2,点击刷新
<html>
<head>
<script>
window.onload = function() {
var che = document.getElementById('v');
che.onclick = function () {
var d = new Date();
this.src = "/aaa/che?time="+d.getTime();
}
}
</script>
<title>Title</title>
</head>
<body>
<form>
<img src="/aaa/che" id="v">
</form>
</body>
</html>