Add cage dependency in 1.pom.xml.
<Dependency> <groupId>Com.github.cage</groupId> <Artifactid>Cage</Artifactid> <version>1.0</version> </Dependency>
Project related information: https://akiraly.github.io/cage/quickstart.html.
2.Controller:@RestController
@RestController
@RequestMapping ("Captcha")
public class Captchacontroller {
@Autowired
Private Captchaservice Captchaservice;
@RequestMapping ("Get")
public void get (HttpServletResponse response,string key) throws IOException {
Response.setcontenttype ("Image/jpeg");//Set the media type of the response so that the browser will recognize that the image is responding
Response.getoutputstream (). Write (Captchaservice.getcaptcha (key));
Response.flushbuffer ();
}
}
3.Service:
@Service ("Captchaservice") Public classCaptchaservice {Private Static FinalLogger log = Loggerfactory.getlogger (captchaservice.class); @Autowired Redisdao Redisdao; Cage Cage=NewGcage (); Public byte[] Getcaptcha (String ID) {if(Stringutils.isblank (id)) {return NULL; } bytearrayoutputstream OS=NewBytearrayoutputstream (); String token= Cage.gettokengenerator (). Next (). SUBSTRING (0, 4); Try{cage.draw (token, OS); Os.close (); } Catch(IOException e) {e.printstacktrace (); } String Key= "captcha-" +ID; Redisdao.getjredis (). Opsforvalue (). Set (key, token); Redisdao.getjredis (). Expire (Key,1, timeunit.hours); returnOs.tobytearray (); } Public BooleanMatchcaptcha (String ID, string captcha) {if(Stringutils.isblank (ID) | |Stringutils.isblank (CAPTCHA)) { return false; } String Key= "captcha-" +ID; String Rediscaptcha=string.valueof (Redisdao.getjredis (). Opsforvalue (). Get (key)); if(Stringutils.isblank (Rediscaptcha)) {return false; } log.info (ID+ "," + Captcha + "," +Rediscaptcha); returnstringutils.equalsignorecase (CAPTCHA, Rediscaptcha); }}
4. Front Page:
$ (' #yzmimg '). attr (' src ', ' https://localhost:8082/captcha/get?key ' +timestamp);
Summary: Setting
Response.setcontenttype ("Image/jpeg") so the return will be in picture form, here is the pit.
Integrate Cage in spring to implement CAPTCHA function