Servlet代碼
package com.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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/checkcode")
public class CheckcodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 1、獲取畫布對象 2、獲取畫筆對象 2.1畫一個實心的矩形,大小和畫布相同 2.2畫一個有邊框的空心矩形 3、提前準備好數據
* ABCDEFGHIJKLMNabcdefghijklmnzxc1234567890 3.1隨機獲取4個數據
* 3.2把隨機獲取的數據畫到畫布上 4、畫干擾線 5、把內存中的驗證碼輸出到客戶端
*/
int width = 120;
int height = 30;
// 獲取畫布對象
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 獲取畫筆對象
Graphics g = image.getGraphics();
//畫一個實心矩形
g.setColor(Color.GRAY);
//設置畫筆的顏色
g.fillRect(0,0, width, height);
//畫一個邊框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
//準備數據
String words = "ABCDEFGHIJKLMNabcdefghijklmnzxc1234567890";
//隨機獲取4個字符
Random random = new Random();
g.setColor(Color.RED);
g.setFont(new Font("隸書",Font.BOLD,20));
//驗證碼第一個字符的座標
int x = 20;
int y = 20;
//獲取words中隨機一個字符的下標
for(int i = 0;i<4;i++){
int index = random.nextInt(words.length());
char ch = words.charAt(index);
//畫到畫布上去
g.drawString(ch+"", x, y);
x+=20;
}
//畫干擾線
g.setColor(Color.BLACK);
int x1,x2,y1,y2;
for(int i = 0;i<4;i++){
x1 = random.nextInt(width);
y1 = random.nextInt(height);
x2 = random.nextInt(width);
y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
// 把圖片輸出到客戶端
ImageIO.write(image, "jpg", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
登錄HTML頁面代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>登錄</h3>
<form action="" method="post">
用戶名:<input type="text" name="username"/><br/>
密碼: <input type="password" name="password"/><br/>
驗證碼:<img id="imgId"alt="驗證碼" src="/Checkcode/checkcode" onclick="changeCode()"><br/>
<input type="submit" value="登錄"/>
</form>
</body>
<script type="text/javascript">
//時間戳
function changeCode(){
var img = document.getElementById("imgId");
img.src = "/Checkcode/checkcode?time="+new Date().getTime();
}
</script>
</html>