One: imageCode.jsp of the generated page
<%@ page contentType="image/jpeg" import="java.util.*,java.awt.*,java.io.*,java.awt.image.*,javax.imageio.*" pageEncoding="utf-8"%>
<%!
Color getRandColor(int fc,int bc){//给定范围获得随机颜色
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);
}
%>
<%
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0); int width=70, height=38;
// create image in memory
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Get graphics context
Graphics g = image.getGraphics();
//Generate random class
Random random = new Random();
//Set 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,28));
//draw Border
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);
// Randomly generate 155 interference lines, so that the authentication code in the image is not easy to be read Other programs detected
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);
}
// Get the randomly generated authentication code (4 digits)
String sRand="";
for (int i=0;i<4;i++){
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
// Display the authentication code in the image
g.setColor(new Color(20+random .nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));// The color from the calling function is the same, maybe because the seeds are too close, so only
g.drawString can be generated directly (rand,13*i+10,28);
}
// Save the authentication code into SESSION
session.setAttribute("rand",sRand);
// Image valid
g.dispose();
OutputStream output=response.getOutputStream( );
// output image to page
ImageIO.write(image, "JPEG", response.getOutputStream());
output.flush();
out.clear();
out = pageContext.pushBody();
%>
2: Display of front-end login.jsp verification code
<img onclick="javascript:loadimage();" title="换一张试试" name="randImage" id="randImage" src="<%=initBasePath%>imageCode.jsp">
Three: Verify the picture switching event
<script language="javascript" type="text/javascript">
function loadimage(){
document.getElementById("randImage").src = "<%=initBasePath%>imageCode.jsp?"+Math.random();
}
</script>
Four: Verify
Get the verification code stored in the session in the background and compare the data in the verification code input box