简单验证码

index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>验证码</title>
		<script type="text/javascript">
			function change() {
				document.getElementById("code").src="RandCode?
                                                 sc="+new Date().getTime();
			}  
      	</script>
	</head>
	<body onload="change()">
		<div>
			<div>
				<img src="" id="code" style="margin-left: 20px"/>
				<button id="btn" style="margin-left: 12px; 
                                        background-color: gray" onclick="change();">
					看不清
				</button>
			</div>
		</div>
	</body>
</html>
RandCode.java:
public class RandCode extends HttpServlet {

	protected static Random random=new Random();  

	@Override 
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
	        throws ServletException, IOException {  
	
		req.setCharacterEncoding("utf-8");  
		resp.setCharacterEncoding("utf-8");  
		
		// 设置输出类型为jpeg图片
		resp.setContentType("image/jpeg"); 
		
		// 验证图片的宽度,高度
		int width = 70;  
		int height = 25; 
		
		Color back = getBack();  
		Color front = getFront(back);  
		String code = getString();  
		
		req.getSession().setAttribute("rand", code);  
		
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);  
		
		Graphics2D g = bi.createGraphics();   // 得到画布
		g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));  // 设置字体
		g.setColor(back);  
		g.fillRect(0, 0, width, height);    // 画背景
		g.setColor(front);  
		g.drawString(code,18,20);           // 画字符
		
		 // 产生至多40个噪点
		for(int i=0, n=random.nextInt(40); i<n; i++){  
		    g.fillRect(random.nextInt(width), random.nextInt(height), 1, 1);  
		}                                  
		
		// 得到二进制输出流
		ServletOutputStream so=resp.getOutputStream();  
		// 对图片进行编码成jpeg格式
		JPEGImageEncoder je=JPEGCodec.createJPEGEncoder(so); 
		je.encode(bi);                      
		so.flush();                         // 刷新缓存
	 }  

	/**
	 * @desc 得到图片背景色
	 */ 
	protected static Color getBack(){  
		return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));  
	}  

	/**
	 * @desc 生成颜色的反色
	 */ 
	protected static Color getFront(Color c){  
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());  
	}  

	/**
	 * @desc 产生随机字符
	 */ 
	protected static String getString(){  
	
	    String old="123456789abcdefghijklmnopqrstuvwxyz"; // 验证图片上面的随机字符
	    StringBuffer sb = new StringBuffer();  
	    
	    int j=0;  
	    for(int i=0; i<4; i++){  
		    j = random.nextInt(old.length());  
		    sb.append(old.substring(j, j+1));  
	    }  
	    return sb.toString();      
	}  
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
    	    throws ServletException, IOException {  
		
		doPost(req,resp);  
	}  
}
启动服务器访问:http://localhost:8080/ValidateCode/

你可能感兴趣的:(简单验证码)