1. 程式人生 > >Servlet 生成驗證碼

Servlet 生成驗證碼

Servlet方法:

public class ValidateCodeServlet extends BaseServlet {
	private static final String	CONTENT_TYPE		= "image/jpeg";

	/**
	 * 數字影象認證系統 隨機產生一個四位的陣列,轉換成圖象輸出 產生的陣列儲存在Session中,繫結名字“rand”
	 * 
	 * @param super.getRequest()
	 * @param super.getResponse()
	 */
	public void createImage(HttpServletRequest request,
			HttpServletResponse response)
	{		
		response.setContentType(CONTENT_TYPE);
		response.setHeader("Pragma","No-cache"); // 設定頁面不快取
		response.setHeader("Cache-Control","no-cache");
		response.setDateHeader("Expires",0);
		try {
			request.setCharacterEncoding("GBK");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		HttpSession session = request.getSession();
		// 產生四位隨機碼,寫入session
		//String chose = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		//去掉容易混淆的字母:0,1,o,I,l,O
		String chose = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
		char display[] = { '0', ' ', '0', ' ', '0', ' ', '0' }, ran[] = { '0', '0', '0', '0' }, temp;
		Random rand = new Random();
		for (int i = 0; i < 4; i++)
		{
			temp = chose.charAt(rand.nextInt(chose.length()));
			display[i * 2] = temp;
			ran[i] = temp;
		}

		String strRandom = String.valueOf(display); // 與String.valueOf(ran)是相同地
		String sRand = request.getParameter("rand"); // 通過傳遞引數來設定驗證碼在session裡的名字
		if (sRand == null)
		{
			sRand = "rand";
		}
		session.setAttribute(sRand,String.valueOf(ran));

		// 生成影象,返回到頁頁上
		int width = 70, height = 26;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		// 以下填充背景顏色
		g.setColor(Color.white);
		g.setColor(getRandomColor(200,250));
		// 設定邊框
		g.fillRect(0,0,width,height);

		// 設定字型顏色、字型
		g.setColor(Color.black);
		g.drawRect(0,0,width - 1,height - 1); // 字要比影象邊框小一點

		// 將認證碼寫入影象
		g.setColor(Color.black);
		g.setFont(new Font("Arial", Font.PLAIN, 18));
		g.drawString(strRandom,1,18);
		// 影象生效
		g.dispose();
		// 輸出影象
		try
		{			
			ImageIO.write(image,"JPEG",response.getOutputStream());
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}		
	}

	/**
	 * 生成隨機顏色
	 * 
	 * @param fc
	 *            前景色
	 * @param bc
	 *            背景色
	 * 
	 * @return Color物件,此Color物件是RGB形式的。
	 */
	public Color getRandomColor(int fc, int bc)
	{
		Random random = new Random();
		if (fc > 255)
		{
			fc = 200;
		}
		if (bc > 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);
	} 
}
頁面:
<script type="text/javascript">
			jQuery(function(){
				jQuery('#urMobile').focus(); 
				//為驗證碼圖片繫結單擊事件 
				jQuery("#imagepic").click(function(){
					this.src="<%=path%>/ValidateCodeServlet.do?method=createImage×tamp="+Math.random();
				});
			});   
		</script>
<tr>
								<td align="right" height="40">
									驗證碼: 
								</td>
								<td align="left">
									<input type="text" size="7" name="code" id="code"/>
									<img src="<%=path%>/ValidateCodeServlet.do?method=createImage" id="imagepic" 
									width="75" height="24" maxlength="4" title="點選圖片,更換驗證碼"/>
								</td>   
							</tr>

效果圖: