代碼實現(xiàn)簡單的生成隨機驗證碼小程序
2020-09-27|HiShop
導讀:在小程序應用中,我們會遇到隨機驗證碼圖片,那么如何使用代碼實現(xiàn)一個簡單的生成隨機驗證碼的小程序...
在小程序應用中,我們會遇到隨機驗證碼圖片,那么如何使用代碼實現(xiàn)一個簡單的生成隨機驗證碼的小程序

//隨機生成驗證碼
//第一步:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test(response);
}
private void test(HttpServletResponse response) throws IOException {
int width = 120,height=25;
//生成一張圖片 此時得到一張寬120,長25的一張黑色圖片
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics grap = img.getGraphics();//得到一個畫筆
//填充背景色
grap.setColor(Color.pink);
//設置填充的區(qū)域
grap.fillRect(1, 1, width-2, height-2);
//設置邊框的顏色 同填充背景顏色 靠近誰是設置哪個屬性的顏色
grap.setColor(Color.red);
grap.drawRect(0, 0, width-1, height-1);
//設置字體
grap.setFont(new Font("黑體", Font.BOLD|Font.ITALIC, 18));
//向圖片上寫字 嘿嘿隨機生成了字符串
Random r = new Random();
int p = 15;
for(int i=1;i<=4;i++)
{
grap.drawString(r.nextInt(10)+"", p,20);
p+=15;
}
//向圖片上畫線
for(int i=1;i<=10;i++)
{
grap.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
//把圖片發(fā)送給客戶端
ImageIO.write(img, "jpg", response.getOutputStream());
}
//第二部:新建login.html
<!DOCTYPE html>
<html>
<head>
<title>login.html</title>
<script type="text/javascript">
function ff(){
var img = document.getElementById("image");
img.src="/day33_response/demo4?user=1"+new Date().getTime();
// img.setAttribute("src","/day33_response/demo4?user="+new Date().getTime());
}
</script>
</head>
<body>
<form action="#" method="get">
用戶名<input type="text" name="uname"><br/><br/>
密 碼<input type="password" name="pwd"><br/><br/>
驗證碼<input type="text" name="code">
<!-- 如果image沒有寫src頁面剛加載時沒有東西,刷新之后才會顯示驗證碼圖片 -->
<img id="image" src='/day33_response/demo4'>
<!-- 換兩行 -->
<a href="javascript:ff()">換一張</a><br/> <br/>
<input type="submit" value="提交">
</form>
</body>
</html>
// 大功告成就可以發(fā)布到tomcat上瀏覽了
//此處介紹一種懶人方法,在doGet方法中,其中ValidateCode四個函數(shù)分別是矩形的寬、高以及驗證碼的個數(shù)和干擾線的條數(shù),然后第一步的函數(shù)就可統(tǒng)統(tǒng)省略了
ValidateCode code = new ValidateCode(320, 25, 4, 8);
code.write(response.getOutputStream());
//注:導相應的ValidateCode的JAR包喔。
您可能感興趣:小程序開發(fā)

立即掃碼關注

多門店/直營/加盟連鎖管理系統(tǒng)