A simple example of implementing the jsp captcha

  • 2020-05-27 06:55:37
  • OfStack

<%@ page language="java" pageEncoding="gbk"%>
<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
Color getRandColor(int fc,int bc){// Get a random color for a given range 
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
// Set the page not to be cached 
response.setDateHeader("Expires", 0);
//  Create an image in memory 
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//  Get graphic context 
Graphics g = image.getGraphics();
// Generate random class 
Random random = new Random();
//  Setting the background color 
g.fillRect(0, 0, width, height);
// Set the font 
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
// Picture frame 
//g.setColor(new Color());
//  Randomly generated 155 Interference line, so that the authentication code in the image is not easily detected by other programs 
for (int i=0;i<155;i++)
 int x = random.nextInt(width);
 int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
//  Take the randomly generated authentication code (4 A digital )
String sRand="";
for (int i=0;i<4;i++){
    String rand=String.valueOf(random.nextInt(10));
    //  Displays the authentication code in the image 
    g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
// Call the function out of the same color, perhaps because the seed is too close, so can only be generated directly 
//  Store the authentication code SESSION

//  The image effect 
//  Output image to page 
ImageIO.write(image, "JPEG", response.getOutputStream());

Page reference:

<td width="62" valign="bottom"><div align="left"><img name="img" id="img" border=0 src="index/image.jsp" onclick="this.src='index/image.jsp?'+Math.random();" /></div></td>



Get the verification code when logging in:

        String randb = (String) request.getSession().getAttribute("rand");

Related articles: