前端
<html>
<head>
<title>登录</title>
<script>
onload = function () {
imgCode.onclick = function () {
this.src = "valid?" + new Date().getTime();
}
}
</script>
</head>
<body>
<form action="login">
<p>
<label for="name">用户名:</label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="password">密码:</label>
<input type="password" name="password" id="password">
</p>
<p>
<label for="code">验证码:</label>
<input type="text" name="code" id="code">
<img id="imgCode" src="valid" title="看不清楚,点击换一张">
</p>
<p>
<button formmethod="post">登陆</button>
<button type="reset">重置</button>
</p>
</form>
</body>
</html>
controller
package com.java.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
@Controller
public class ValidCodeController {
@RequestMapping("valid")
public void validCode(HttpSession session, OutputStream out) throws Exception {
Random rnd = new Random();
String code = "";
for (int i = 0; i < 4; i++) {
int n = rnd.nextInt(62);
if (n < 10) {
code += n;
} else if (n < 36) {
code += (char) (n - 10 + 'A');
} else {
code += (char) (n - 36 + 'a');
}
}
session.setAttribute("code", code);
BufferedImage image = new BufferedImage(
100, 25, BufferedImage.TYPE_INT_RGB);
Graphics gra = image.getGraphics();
gra.setColor(Color.yellow);
gra.fillRect(2, 2, 96, 21);
gra.setFont(new Font("Times New Roman", Font.BOLD | Font.ITALIC, 20));
for (int i = 0; i < 4; i++) {
Color clr = new Color(rnd.nextInt(256),
rnd.nextInt(256), rnd.nextInt(256));
gra.setColor(clr);
gra.drawString(code.substring(i, i + 1), 15 + 20 * i, 18);
}
for (int i = 0; i < 5; i++) {
Color clr = new Color(rnd.nextInt(256),
rnd.nextInt(256), rnd.nextInt(256));
gra.setColor(clr);
Graphics2D g2d = (Graphics2D) gra;
g2d.setStroke(new BasicStroke(1 + rnd.nextFloat() + rnd.nextInt(2)));
gra.drawLine(rnd.nextInt(100), rnd.nextInt(25),
rnd.nextInt(100), rnd.nextInt(25));
}
ImageIO.write(image, "jpeg", out);
out.close();
}
}