做開發時很多地方都會用到驗證碼,至於驗證碼是什麼就不多說,各式各樣的驗證碼都有(ps:12306那個驗證碼感覺怎麼樣),這次就寫一下如何製作一個簡單的驗證碼
html代碼如下:
<html>
<head>
<title>$Title$</title>
</head>
<body>
<img id="pin" src="<%=request.getContextPath()%>/PIN.html?tip=1">
</body>
</html>
效果如圖:
java後臺代碼如下:
@Controller
public class TestController {
@RequestMapping("/PIN")
public void pin(HttpServletResponse response, HttpSession session) throws IOException {
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");//說明請求生成的響應是圖片
int width=100, height=22;//定義圖片寬高
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();//獲取畫筆
Random random = new Random();
Color[] colors = new Color[]{Color.BLUE,Color.BLACK,Color.GREEN,Color.RED};//設置了四種字體的顏色
//背景色填充
g.setColor(new Color(240,240,240));
g.fillRect(1, 1, width-1, height-1);
//邊緣顏色設置
g.setColor(new Color(102,102,102));
g.drawRect(0, 0, width-1, height-1);
g.setFont(new Font("Times New Roman", Font.PLAIN, 17));//設置字體
//畫干擾線
g.setColor(new Color(220,220,220));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g.drawLine(x,y,x + xl,y + yl);
}
//驗證碼的字符來源,也可以用漢字,這裏就只用數字加字母了
char[] source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
//生成隨機字符串
String pinNum = "";
for (int i=0;i<6;i++)
{
int itmp = random.nextInt(source.length);
pinNum += source[itmp];
g.setColor(colors[random.nextInt(colors.length)]);
g.drawString(String.valueOf(source[itmp]),15*i+10,16);
}
//將字符串存入session中,以便後面做驗證
session.setAttribute("equals_pin",pinNum);
g.dispose();//銷燬圖形界面資源
ImageIO.write(image, "JPEG", response.getOutputStream());//將圖片寫入response的輸出流
}
}