---
title: "jsp 实现验证码"
author: "1336224635"
date: "2012-04-13T13:29:48Z"
tags: ["jsp 验证码"]
categories: ["行业应用"]
slug: "jsp"
draft: false
lastmod: "2012-05-08T08:39:34Z"
id: 1485170
url: "https://andy2019.iteye.com/blog/1485170"
---

**一.新建image.jsp文件**

&lt;%@ page import="java.awt.\*,java.awt.image.\*,java.util.\*,javax.imageio.\*"%&gt;

&lt;%@ page import="java.io.OutputStream"%&gt;

&lt;%!Color getRandColor(int fc, int bc) {

Random random = new Random();

if (fc &gt; 255)

fc = 255;

if (bc &gt; 255)

bc = 255;

int r = fc + random.nextInt(bc - fc);

int g = fc + random.nextInt(bc - fc);

int b = fc + random.nextInt(bc - fc);

return new Color(r, g, b);

}%&gt;

&lt;%

try {

response.setHeader("Pragma", "No-cache");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

int width = 60, height = 20;

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE\_INT\_RGB);

OutputStream os = response.getOutputStream();

Graphics g = image.getGraphics();

Random random = new Random();

g.setColor(getRandColor(200, 250));

g.fillRect(0, 0, width, height);

 

g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

g.setColor(getRandColor(160, 200));

for (int i = 0; i &lt; 155; i++) {

int x = random.nextInt(width);

int y = random.nextInt(height);

int xl = random.nextInt(12);

int yl = random.nextInt(12);

g.drawLine(x, y, x + xl, y + yl);

}

String sRand = "";

for (int i = 0; i &lt; 4; i++) {

String rand = String.valueOf(random.nextInt(10));

sRand += rand;

g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));

g.drawString(rand, 13 * i + 6, 16);

}

System.out.println(sRand);

session.setAttribute("rand", sRand);

g.dispose();

 

ImageIO.write(image, "JPEG", os);

os.flush();

os.close();

os = null;

response.flushBuffer();

out.clear();

out = pageContext.pushBody();

} catch (IllegalStateException e) {

System.out.println(e.getMessage());

e.printStackTrace();

}

%&gt;

 

 

二.在需要引入的地方

 

&lt;tr style="height: 22px"&gt;

&lt;td&gt;

&lt;font color="#FFFFFF"&gt;验证码：&lt;/font&gt;

&lt;/td&gt;

&lt;td  width="200"&gt;

&lt;input id="codeInputFront"  class="inputText" type="text" style="width: 50px" /&gt;

&lt;img id="LoginImgVerifyCode" style="float: left; src="jsp/frontstage/index/image.jsp" /&gt;

&lt;a href="javascript:changeVerifyCode()"&gt;刷新&lt;/a&gt;

&lt;/td&gt;

&lt;/tr&gt;

 

注意：&lt;image&gt;标签中要写相对路径。但是一定是写全，基于WebRoot 目录下方