仅限于实现验证码,没有完善登录操作,验证码生成的代码理解就好,里面很多的类和方法都不常用,不同形式的验证码代码网上有很多,都可以直接用。如果有问题欢迎评论
效果
前端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function changeImage(){
document.getElementById("myimg").src="CheckCodeServlet?a="+Math.random();
}
</script>
</head>
<body>
<h1>欢迎登录</h1>
<form method="post">
账号 <input type="text" name="username"/><br/>
密码 <input type="password" name="password"/><br/>
验证码<input type="text" size="12" name="checkcode"/><img src="CheckCodeServlet" id="myimg"/><a href="javascript:changeImage()" >看不清?换一张</a><br/>
<input type="submit" value = "登录" />
</form>
</body>
</html>
验证码实现Servlet
package com.yht.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckCodeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int height = 25;
int width = 60;
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
//2 创建一个图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//3 获得画板
Graphics g = image.getGraphics();
//4 填充一个矩形
// * 设置颜色
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(Color.WHITE);
g.fillRect(1, 1, width-2, height-2);
// * 设置字体
g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 25));
//5 写随机字
for(int i = 0 ; i < 4 ; i ++){
// 设置颜色--随机数
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
// 获得随机字
int index = random.nextInt(data.length());
String str = data.substring(index, index + 1);
// 写入
g.drawString(str, width/6 * (i + 1), 20);
}
//6 干扰线
for(int i = 0 ; i < 3 ; i ++){
// 设置颜色--随机数
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
// 随机绘制先
g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),random.nextInt(height));
// 随机点
g.drawOval(random.nextInt(width), random.nextInt(height), 2, 2);
}
//end 将图片响应给浏览器
ImageIO.write(image, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}