需求: 在访问登录页面时,需要生产验证码。从而防止用户使用程序恶意登录。
代码演示:
1.页面代码:
<html>2.Servlet代码
<head>
<title>登录页面</title>
<style type="text/css">
.biao{
500px;
height: 300px;
border: 2px solid black;
margin: 100px auto;
align-items: center;
}
.login{
margin: 0 auto;
}
</style>
</head>
<body>
<form action="/web11/userlogin" method="post" class="biao">
<!--登录页面-->
<div class="login" >
用户名:<input type="text" class="userName" name="userName" value="" placeholder="请输入用户名"></br>
密 码:<input type="password" name="passWord" value="" placeholder="请输入密码"></br>
验证码:<input type="text" class="userName" name="userName" value="" placeholder="请输入验证码">
</div>
<!--请输入验证码-->
<div class="form-group">
<div class="col-sm-3">
<img src="/web11/checkcode" onclick="changeImg(this)"/>
</div>
</div>
<!--提交登录-->
<input type="submit" value="登录" >
</form>
</body>
<!--点击刷新验证码-->
<script type="text/javascript">
function changeImg(obj) {
// alert("切换验证码");
//修改修改src
obj.src = "/web11/checkcode?time=" + Date.now();
}
</script>
</html>@WebServlet(urlPatterns = "/checkcode")
public class CheckServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String t = request.getParameter("t");
System.out.println("time : " + t);
// 生成随机字符 ,打印到控制台
String code = getCodeString();
System.out.println(code);
// 生成图片
BufferedImage checkImg = ImgUtils.getCheckImg(code);
// 将画布显示在浏览器中
ImageIO.write(checkImg, "jpg", response.getOutputStream());
}
public String getCodeString() {
// 准备数据
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
// 准备随机对象
Random r = new Random();
// 声明一个变量 保存验证码
StringBuilder code = new StringBuilder();
// 书写4个随机字符
for (int i = 0; i < 4; i++) {
// 将新的字符 保存到验证码中
code.append(data.charAt(r.nextInt(data.length())));
}
return code.toString();
}
}
3.工具类代码
package util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class ImgUtils {
public static BufferedImage getCheckImg(String code) {
Random r = new Random();
// 创建画布
int width = 120;
int height = 40;
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);// 获得画笔
Graphics g = bufferedImage.getGraphics();
// 填充背景颜色
g.setColor(Color.orange);
g.fillRect(0, 0, width, height);
// 绘制边框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
// 设置字体
g.setFont(new Font("宋体", Font.BOLD, 28));
// 绘制干扰线
for (int i = 0; i < 6; i++) {
// 设置随机颜色
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width),
r.nextInt(height));
}
// 书写4个字符
for (int i = 0; i < 4; i++) {
String ch = code.charAt(i) + "";
// 设置随机颜色
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.drawString(ch, 10 + i * 28, 30);
}
return bufferedImage;
}
}