package com.ekexiu.portal.util;

import java.io.IOException;  

import javax.servlet.Servlet;
import javax.servlet.ServletException;  
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

public class PictureVC extends HttpServlet implements Servlet {  
  
	private static final long serialVersionUID = 2459158903781864570L;

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
          
        //生成随机字串  
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //获取上次请求发送的rand的cookie 设置生命为0.
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
			if("rand".equalsIgnoreCase(cookie.getName())){
				cookie.setMaxAge(0);
			}
		}
        //为随机数创建cookie
        Cookie rand = new Cookie("rand", verifyCode.toLowerCase());
        //设置cookie中随机数的过期时间为1小时
        rand.setMaxAge(60 * 60);
        //在响应头中添加cookie
        response.addCookie(rand);
        //生成图片  
        int w = 100, h = 40;  
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);  
  
    }  
} 
