May 30, 2021 Article blog
<html><body>
<form method=post action="result.jsp">
<input type=text name=input maxlength=4>
<img border=0 src="image.jsp">
<input type="submit"value="submit">
</form></body></html>
<%@ page contentType="image/JPEG"
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"
pageEncoding="GBK"%>
Get random colors for a given range
<%!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);
}%>
<%
The settings page is not 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 the graphics context
Graphics g = image.getGraphics();
Create a random class
Random random = new Random();
Set the background
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
Set the font
g.setFont(new Font("Times New Roman", Font.PLAIN,18));
Draw the border
//g.setColor(newColor());
//g.drawRect(0,0,width⑴,height⑴);
Randomly generated 155 interference lines, so that the authentication code in the image is not easy to detect by other programs
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 100; 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 randomly generated authentication codes (4 digits)
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 functions come out of the same color, mostly because the seeds are too close, so can only be generated directly
g.drawString(rand, 13 * i + 6,16);
}
Deposit the authentication code into SESSION
session.setAttribute("code",sRand);
The image takes effect
g.dispose();
Output the image to the page
ImageIO.write(image, "JPEG",response.getOutputStream());
%>
<%@ page language="java"import="java.util.*" pageEncoding="GBK"%>
<html><body>
<%
String input=request.getParameter("input");
String code=(String)session.getAttribute("code");
if(input.equals(code)){
out.println("验证成功!");
}else{
out.println("验证失败!");
}
%>
</body></html>
Your eclipse will prompt you: there's something wrong with the graphic.drawString() method
It's your jdk version that's too high, but it doesn't matter. Just lower the compatible version of this project.
How to do this:
Right-click process, select propriety, and then select Java compiler
Drop the compatible version of jdk to 1.4