Java Web实现加减乘除验证码完整代码
时间: 2024-05-03 19:17:10 浏览: 138
下面是一个使用 Java Web 实现加减乘除验证码的完整代码示例:
index.jsp:
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证码</title>
</head>
<body>
<form action="checkCode.jsp" method="post">
<label>请输入计算结果:</label>
<input type="text" name="code"/>
<img src="getCheckCode.jsp" alt="验证码"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
```
getCheckCode.jsp:
```jsp
<%@ page contentType="image/jpeg" language="java" %>
<%@ page import="java.awt.*" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="java.util.Random" %>
<%@ page import="javax.imageio.ImageIO" %>
<%
int width = 100;
int height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.PLAIN, 20));
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);
}
String[] operators = {"+", "-", "*", "/"};
String operator = operators[random.nextInt(operators.length)];
int num1 = random.nextInt(100);
int num2 = random.nextInt(100);
String mathExpression = num1 + operator + num2 + "=?";
int result;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
result = 0;
break;
}
session.setAttribute("checkCode", result);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(mathExpression, 5, 25);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
// 生成随机颜色
private 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);
}
%>
```
checkCode.jsp:
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证码</title>
</head>
<body>
<%
int userCode = Integer.parseInt(request.getParameter("code"));
int checkCode = (int) session.getAttribute("checkCode");
if (userCode == checkCode) {
%>
<h2>验证码正确!</h2>
<%
} else {
%>
<h2>验证码错误!</h2>
<%
}
%>
</body>
</html>
```
在这个示例中,我们使用了 `getCheckCode.jsp` 来生成一个包含计算结果的验证码图片,并将其显示在 `index.jsp` 页面上。当用户在 `index.jsp` 页面上输入验证码并提交时,我们会在 `checkCode.jsp` 页面上验证用户输入是否正确,并输出相应的结果。
请注意,这个示例中使用了 JSP 技术来实现 Java Web 应用程序,但是在实际开发中,我们更倾向于使用 Servlet 和 JSP 的组合来实现 Java Web 应用程序。
阅读全文