Java generates captcha
- 2020-06-07 04:29:03
- OfStack
The process of Java generating captcha is as follows:
Received request - > Random number used to generate captcha - > Use random Numbers to write the picture - > Record the random number to Session - > Output verification code
The process of Java verification verification code is as follows:
Received request - > Gets the captCHA number sent by the user - > Verify that it is correct - > Output verification results
The captcha generation process is illustrated by an example that USES the Rest interface of the basic Java Spring framework and can be obtained using any platform:
Examples of server processing captcha:
1. Receive verification code request:
/**
* Receive a verification code request
*/
@RequestMapping(value="captchacode")
public void CaptchaCode(){
try {
CaptchaCodeModel captchaCodeModel=new CaptchaCode().getCode();
// Put the verification code to Session In the
HttpServletRequest httpServletRequest=super.getRequest();
httpServletRequest.getSession().setAttribute("captchacodekey", captchaCodeModel.getCaptchaCode());
// Write the image to the client
HttpServletResponse httpServletResponse=super.getResponse();
// Prohibit the cache
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
// The output image
ImageIO.write(captchaCodeModel.getCaptchaImage(), "jpeg", servletOutputStream);
servletOutputStream.close();
} catch (Exception e) {
logger.info(" Captcha generation failed :"+e.getMessage());
}
}
2. Generate captchas and images:
public class CaptchaCode {
private int width = 90;// Defining the image width
private int height = 20;// Defining the image height
private int codeCount = 4;// Defines the number of captchas displayed on the image
private int xx = 15;
private int fontHeight = 18;
private int codeY = 16;
char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public CaptchaCodeModel getCode() throws IOException {
// Define the image buffer
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics gd = buffImg.getGraphics();
// create 1 Random number generator class
Random random = new Random();
// Fill the image with white
gd.setColor(Color.WHITE);
gd.fillRect(0, 0, width, height);
// Create a font. The font size should be based on the height of the image.
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
// Set the font.
gd.setFont(font);
// Picture frame.
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
// Randomly generated 40 An interference line that makes the authentication code in the image difficult to be detected by other programs.
gd.setColor(Color.BLACK);
for (int i = 0; i < 40; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
gd.drawLine(x, y, x + xl, y + yl);
}
// randomCode Used to save randomly generated captcha for user authentication after login.
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// Randomly generated codeCount A verification code for a number.
for (int i = 0; i < codeCount; i++) {
// Get the randomly generated captCHA number.
String code = String.valueOf(codeSequence[random.nextInt(36)]);
// Generate random color components to construct color values so that each number output has a different color value.
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// The captcha is drawn into the image with a randomly generated color.
gd.setColor(new Color(red, green, blue));
gd.drawString(code, (i + 1) * xx, codeY);
// Will produce the 4 Random number combination in 1 Up.
randomCode.append(code);
}
CaptchaCodeModel captchaCodeModel=new CaptchaCodeModel();
captchaCodeModel.setCaptchaCode(randomCode.toString());
captchaCodeModel.setCaptchaImage(buffImg);
return captchaCodeModel;
}
public class CaptchaCodeModel{
// The verification code String In the form of
private String captchaCode;
// The image form of captcha
private BufferedImage captchaImage;
public String getCaptchaCode() {
return captchaCode;
}
public void setCaptchaCode(String captchaCode) {
this.captchaCode = captchaCode;
}
public BufferedImage getCaptchaImage() {
return captchaImage;
}
public void setCaptchaImage(BufferedImage captchaImage) {
this.captchaImage = captchaImage;
}
}
3. Receive the verification code from the user and verify:
/**
* Verification verification code
*/
@RequestMapping(value = "valicatpcha")
public void register_R() {
PageData pageData = super.getPageData();
// Get verification code
String captchaCode = pageData.getString("captchacode");
HttpServletRequest httpServletRequest = super.getRequest();
Object codeObject = httpServletRequest.getSession().getAttribute( " captchacodekey " );
// Verification code error
if (codeObject == null
|| Tools.isEmptyString(captchaCode)
|| !String.valueOf(codeObject).toUpperCase()
.equals(captchaCode.toUpperCase())) {
setResult(
MessageManager.getInstance().getMessage("invalidcaptcha"),
ResultType.Error);
return;
}
}
Page request verification code and verification examples:
- Request verification code: < img src='captchacode' style='height:32px;width:148px;'
- Verification verification code:
function validcaptchacode(captchaCode) {
$.ajax({
type : "POST",
url : "valicatpcha",
data : {
captchacode : captchaCode,
tm : new Date().getTime()
},
dataType : "json",
cache : false,
success : function(data) {
alert(data);
},
error : function(data) {
alert(data); }
});
}