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;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Random;
@WebServlet("/zm")
public class yzm extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width=300;//设置宽度
int height=150; //设置高度
BufferedImage buff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//设置画笔工具用于画图形
Graphics g = buff.getGraphics();
//设置底色
g.setColor(Color.cyan);
g.fillRect(0,0,width,height);
//设置干扰线条
g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);
//生成随机所需要的验证码
String str="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
//生成随机字母
Random random = new Random();
for (int i = 1; i <= 4; i++) {
int i1 = random.nextInt(str.length());
char c = str.charAt(i1);
g.drawString(c+"",width/5*i,height/2);
}
g.setColor(Color.GREEN);
for (int i = 0; i < 10; i++) {
int i1 = random.nextInt(width);
int i2 = random.nextInt(width);
int i3 = random.nextInt(height);
int i4 = random.nextInt(height);
g.drawLine(i1,i3,i2,i4);
}
ImageIO.write(buff,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
} |
|