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.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
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.setColor(getRandColor(200,250));
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());
//g.drawRect(0,0,width-1,height-1);
// Randomly generated 155 Interference line, so that the authentication code in the image is not easily detected by other programs
g.setColor(getRandColor(160,200));
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);
g.drawLine(x,y,x+xl,y+yl);
}
// 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));
sRand+=rand;
// 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
g.drawString(rand,13*i+6,16);
}
// Store the authentication code SESSION
session.setAttribute("rand",sRand);
// The image effect
g.dispose();
// Output image to page
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
%>
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>
JS:
this.src='index/image.jsp?'+Math.random();
Get the verification code when logging in:
String randb = (String) request.getSession().getAttribute("rand");