java servlet 返回图片验证码

java servlet 返回图片验证码 ,用于注册、登录场景,使用图片验证码防止爆破攻击
实际使用要注意在java后台每次取到验证码比较验证码是否正确时都需要把图片验证码清空掉,
否则拿到一个验证码依然可以一直爆破攻击

CheckCodeServlet.java

package com.gaom.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckCodeServlet extends HttpServlet {
	
	private static  int width=94;
	private static int height=38;
	private static int codeCount=4;
	private static int lineCount=30;
	private int code;
	
	
	
	private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J','K',   
			'M', 'N',  'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y',   
			   '2', '3', '4', '5', '6', '7', '8', '9' }; 

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
		OutputStream os=null;
		try{
			
			os=response.getOutputStream();
			Map map=new HashMap();
		BufferedImage bufferedImage=createCode(map);
		String randomCode=map.get("randomCode")+"";
		HttpSession httpSession=request.getSession();
					httpSession.removeAttribute("randomCode");
					httpSession.setAttribute("randomCode", randomCode);
					httpSession.setMaxInactiveInterval(3600);
		System.out.println("随机生成的验证码为:"+ randomCode);
		
		
		// 设置响应的类型格式为图片格式  
        response.setContentType("image/jpeg");  
        //禁止图像缓存。  
        response.setHeader("Pragma", "no-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0); 
		
		ImageIO.write(bufferedImage, "png",os);
		
		
		
		
		  
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(os!=null){
				os.close();
			}
		}
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

	public void init() throws ServletException {
		
	}
	
	
	private BufferedImage createCode(Map map){
		int x=17,fontHeight=25,codeY=30,red=0,green=0,blue=0;
		BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		 Graphics2D 	graphics2d=		bufferedImage.createGraphics();
		 Random random=new Random();
		 	 graphics2d.setColor(Color.white);
		 	 graphics2d.fillRect(0,0, width, height);
		 	 Font font = new Font("Algerian", Font.ITALIC, fontHeight);  
		 	 graphics2d.setFont(font);
		 	 for(int i=0;i<lineCount;i++){
		 		 
		 		int xs = random.nextInt(width);  
		 		int ys = random.nextInt(height);  
		 		int xe = xs+random.nextInt(width/8);  
		 		int ye = ys+random.nextInt(height/8);
		 		 
		 		 red=random.nextInt(255);
		 		 green=random.nextInt(255);
		 		 blue=random.nextInt(255);
		 		 graphics2d.setColor(new Color(red,green,blue));
		 		 graphics2d.drawLine(xs, ys, xe, ye);
		 		 
		 	 }
		 	StringBuffer randomCode = new StringBuffer(); 
		 	for(int i=0;i<codeCount;i++){
		 		String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
		 		red = random.nextInt(255);  
		 		green = random.nextInt(255);  
		 		blue = random.nextInt(255);  
		 		graphics2d.setColor(new Color(red, green, blue));  
		 		graphics2d.drawString(strRand, (i + 1) * x, codeY);  
		 		randomCode.append(strRand);  
		 	}
		 	map.put("randomCode", randomCode.toString());
		 	
		 	 bufferedImage.flush();
		 	
		 	 return bufferedImage;
		
	}

}

web.xml 增加servlet-mapping

web3.0以后也可以直接在CheckCodeServlet.java上使用servlet注解形式

 
        <servlet-mapping>
        	<servlet-name>CheckCodeservlet-name>
        	<url-pattern>/checkCodeurl-pattern>
        servlet-mapping>

你可能感兴趣的:(java,web,java,servlet,开发语言)