第一中驗證碼:
使用者登入驗證碼代碼示例第一中驗證碼:第二中驗證碼:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX1MGVNBTQq1UMFpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DN5ETMyQDM5AjMygDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
一.驗證碼實作代碼
通過BufferedImage類進行繪制:
package com.igeek.web;
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;
/**
* 驗證碼的Servlet
*/
@WebServlet("/verification.jpg")
public class VerificationCodeServlet extends HttpServlet {
//随機
private final Random rm = new Random();
/**
* 通路的時候 動态的建立一張圖檔
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width = 100;
int height = 50;
//建立一個圖檔對象
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//擷取繪圖對象
Graphics g = image.getGraphics();
//繪制背景 繪制一個 填充的矩形
g.setColor(Color.WHITE); //設定畫筆的顔色
g.fillRect(0, 0, width, height); //繪制填充的矩形
g.setColor(Color.RED);
g.drawRect(0, 0, width-2, height-2); //繪制矩形框
//繪制一些幹擾 點
for(int i=0;i<100;i++) {
g.setColor(new Color(rm.nextInt(255),rm.nextInt(255),rm.nextInt(255)));
g.fillOval(rm.nextInt(width), rm.nextInt(height), 3, 3);
}
//繪制幹擾線
for(int i=0;i<50;i++) {
g.setColor(new Color(rm.nextInt(255),rm.nextInt(255),rm.nextInt(255)));
g.drawLine(0, rm.nextInt(height), rm.nextInt(width), rm.nextInt(height));
}
g.setFont(new Font("黑體", Font.BOLD, 30)); //設定字型
//随機産生的驗證碼
String source = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456790";
String code = "";
for(int i=0;i<4;i++) {
String s = source.charAt(rm.nextInt(source.length()))+"";
//繪制文字
g.setColor(new Color(rm.nextInt(255),rm.nextInt(255),rm.nextInt(255)));
g.drawString(s, 10+i*23, 35);
code+= s;
}
System.out.println("code="+code);
//存入會話
request.getSession().setAttribute("Code", code);
//輸出圖檔
ImageIO.write(image, "jpg", response.getOutputStream());
}
}
二.驗證碼校驗
package com.igeek.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 校驗驗證碼的Servlet
*/
@WebServlet("/check.do")
public class CheckVerificationCodeServlet extends HttpServlet {
/**
* 傳遞一個輸入的值,驗證和會話中存放的驗證碼是否一緻
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String str_code = request.getParameter("str_code");
//得到會話
HttpSession session = request.getSession();
String code = (String)session.getAttribute("Code");
code = code==null?"":code;
response.getWriter().print(code.equals(str_code));
}
}
三.頁面
<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>頁面标題</title>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
//校驗輸入框中輸入的驗證碼是否正确
$(function(){
$("#varification").blur(function(){
//
$.get("check.do",{"str_code":$(this).val()},function(rs){
console.log(rs);
if(rs=='true'){
$("#sp").css({"color":"green"}).text("OK");
}else{
$("#sp").css({"color":"red"}).text("ERROR");
}
})
});
});
//點選換驗證碼圖檔 注意:每次更換圖檔的src值必須不同,這裡拼接随機數 Math.random()
function changeImg(){
var vv = document.getElementById("varificationCode");
vv.src="verification.jpg?rm"+Math.random();
}
</script>
</head>
<body>
<input id="varification" placeholder="請輸入驗證碼">
<a href="JavaScript:changeImg();" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<img alt="驗證碼" id="varificationCode" src="verification.jpg">
</a>
<a href="JavaScript:changeImg();" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >看不清楚,換一張?</a>
<br>
<span id="sp"></span>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
第二中驗證碼:
代碼
/**
* 擷取驗證碼
*
* @param request a
* @param response a
* @return a
*/
public ModelAndView getValiYard(HttpServletRequest request,
HttpServletResponse response)
{
try
{
// 設定頁面不緩存
BaseMultiController.initSet(request, response);
String valiyard = request.getParameter("valiyard");
HttpSession session = request.getSession(true);
// 在記憶體中建立圖象
int width = 90;
int height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 擷取圖形上下文
Graphics g = image.getGraphics();
// 生成随機類
Random random = new Random();
// 設定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 設定字型
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 随機産生50條幹擾線,使圖象中的認證碼不易被其它程式探測到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 50; i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随機産生的認證碼(6位數字)
String sRand = "";
for (int i = 0; i < 6; i++)
{
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将認證碼顯示到圖象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110))); // 調用函數出來的顔色相同,可能是因為種子太接近,是以隻能直接生成
g.drawString(rand, 13 * i + 6, 16);
}
// 将認證碼存入SESSION
session.setAttribute(valiyard, sRand);
// 圖象生效
g.dispose();
// 輸出圖象到頁面
javax.servlet.ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
out.flush();
out.close();
}
catch (Exception e)
{
logger.writeLog(logger.LOG_LEVEL_ERROR,
logger.getExceptionMethodHint(), e);
}
return null;
}
/**
* 随機的顔色
* @param fc fc
* @param bc bc
* @return a
*/
private Color getRandColor(int fc, int bc)
{ // 給定範圍獲得随機顔色
Random random = new Random();
if (fc > 255)
{
fc = 255;
}
if (bc > 255)
{
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
頁面:
<td style='padding-top: 5px;'>
<img id="checkCodeImg" name="checkCodeImg"
src="servlet/CheckCodeServlet?t=1312795073192"
onclick="javaScript:document.getElementById('checkCodeImg').src='servlet/CheckCodeServlet?t='+(new Date().getTime())" />
</td>