好久没有更新blog了,可能是最近太懒或者太忙,但我觉得这都是借口(2333),最近思考了很多,作为一个技术人员要么学一门去不断的深入,要么去不断的扩展其他技术,所以呢?我选择连个兼顾,嘻嘻!
今天我们看下Web端的校验码是用Java怎么生成的,校验码多用于登录界面,作用无非就是,防止暴力访问,ok,废话不多说,看代码:
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int width = 120;
int height = 25;
//创建内存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
//画笔
Graphics g = image.getGraphics();
//画边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width
, height);
//填充背景色
g.setColor(Color.yellow);
g.fillRect(1, 1, width - 1, height - 2);
//画干扰线
g.setColor(Color.gray);
Random r = new Random();
for (int i = 0; i < 10; i++) {
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
//随机数字
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 20));
int x = 23;
for (int i = 0; i < 4; i++) {
g.drawString(r.nextInt(10) + "", x, 20);
x += 20;
}
//输出到浏览器
ImageIO.write(image, "jpg", resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
代码很easy
我们看下实现效果: