package com.example.demo.controller;
import com.google.code.kaptcha.constants;
import com.google.code.kaptcha.producer;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.getmapping;
import javax.imageio.imageio;
import javax.servlet.servletoutputstream;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
import java.awt.image.bufferedimage;
@controller
public class chacontroller {
@autowired
private producer captchaproducer;
@getmapping("/getkaptchaimage")
public void getkaptchaimage(httpservletresponse response,httpsession session) throws exception {
response.setdateheader("expires", 0);
// set standard http/1.1 no-cache headers.
response.setheader("cache-control", "no-store, no-cache, must-revalidate");
// set ie extended http/1.1 no-cache headers (use addheader).
response.addheader("cache-control", "post-check=0, pre-check=0");
// set standard http/1.0 no-cache header.
response.setheader("pragma", "no-cache");
// return a jpeg
response.setcontenttype("image/jpeg");
// create the text for the image
string captext = captchaproducer.createtext();
// store the text in the session
//request.getsession().setattribute(constants.kaptcha_session_key, captext);
//将验证码存到session
session.setattribute(constants.kaptcha_session_key, captext);
// create the image with the text
bufferedimage bi = captchaproducer.createimage(captext);
servletoutputstream out = response.getoutputstream();
// write the data out
imageio.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}