package com.ssj.framework.core.common.servlet;


import com.ssj.framework.core.common.util.ImageCaptchaUtil;
import com.ssj.sys.util.Constants;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 
 * 类名称：CaptchaServlet
 * 类描述：验证码页面处理<br>
 * @Author:xxxx
 * @version v1.0
 *
 */
@WebServlet(loadOnStartup=1,urlPatterns={"/kaptcha.jpg"})
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = -7732112610258511828L;

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

        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);

        // 设置标准HTTP/1.1无缓存标头
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // 设置IE浏览器扩展标准HTTP/1.1无缓存标头（使用addHeader）
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // 设置标准HTTP/1.0 no-cache头
        response.setHeader("Pragma", "no-cache");

        // 返回一个JPEG
        response.setContentType("image/jpeg");

        // 如果session存在验证码先清除
        if (StringUtils.isNotBlank((String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
            session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        }

        // 创建验证码
        ImageCaptchaUtil vCode = new ImageCaptchaUtil(120, 40, 5);

        // 存储验证码到session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, vCode.getCode());

        ServletOutputStream out = response.getOutputStream();
        // 写数据到前台
        ImageIO.write(vCode.getBuffImg(), "png", out);

        try {
            out.flush();
        } finally {
            out.close();
        }
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
