一 驗(yàn)證碼的由來
灌陽網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,灌陽網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為灌陽千余家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)公司要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的灌陽做網(wǎng)站的公司定做!
在web項(xiàng)目開發(fā)中,為了防止部分人使用自動(dòng)工具(如:自動(dòng)注冊(cè)機(jī))等進(jìn)行批量的數(shù)據(jù)處理,在不同的功能節(jié)點(diǎn)部分,添加了驗(yàn)證碼進(jìn)行驗(yàn)證,達(dá)到對(duì)自動(dòng)軟件的屏蔽效果
最經(jīng)典的應(yīng)用如:網(wǎng)站注冊(cè)圖形驗(yàn)證碼;接下來,通過java技術(shù),結(jié)合servlet實(shí)現(xiàn)一個(gè)網(wǎng)站注冊(cè)需要的圖形驗(yàn)證碼程序,提供大家參考。
二 實(shí)現(xiàn)注冊(cè)頁面圖形驗(yàn)證碼效果
1. 創(chuàng)建web項(xiàng)目:java_servlet_verifyimg
2. 創(chuàng)建自動(dòng)生成圖形驗(yàn)證碼的控制器——VerifyImgServlet
package com.phome.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class VerifyImgServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
// 設(shè)置隨機(jī)字符字典。其中不包含0,o,1,I等難以辨認(rèn)的字符
public static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
public static Random random = new Random(); // 隨機(jī)數(shù)對(duì)象
public static String getRandomString() {
StringBuffer buffer = new StringBuffer(); // 字符串緩存
for (int i = 0; i < 6; i++) // 六次循環(huán)獲取字符
{
buffer.append(CHARS[random.nextInt(CHARS.length)]); // 每次隨機(jī)取一個(gè)字符
}
return buffer.toString();
}
public static Color getRandomColor() {
return new Color(random.nextInt(255), random.nextInt(255),
random.nextInt(255));
}
public static Color getReverseColor(Color c) {
return new Color(255 - c.getRed(), 255 - c.getGreen(),
255 - c.getBlue());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg"); // 設(shè)置輸出類型 不可省略
String randomString = getRandomString(); // 調(diào)用生成隨機(jī)字符串方法獲取并接受隨機(jī)字符串
request.getSession(true).setAttribute("randomString", randomString); // 將字符串存儲(chǔ)到Session中
int width = 100; // 圖片寬度
int height = 30; // 圖片高度
Color color = getRandomColor(); // 獲取隨機(jī)顏色 用于背景色
Color reverse = getReverseColor(color); // 反色 用于前景色
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB); // 創(chuàng)建一個(gè)彩色圖片
Graphics2D g = bi.createGraphics(); // 獲取繪圖對(duì)象
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16)); // 設(shè)置字體
g.setColor(color); // 設(shè)置顏色
g.fillRect(0, 0, width, height); // 繪制背景
g.setColor(reverse); // 設(shè)置顏色
g.drawString(randomString, 18, 20); // 繪制隨機(jī)字符
for (int i = 0, n = random.nextInt(100); i < n; i++) // 畫最多一百個(gè)噪音點(diǎn)
{
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); // 隨機(jī)噪音點(diǎn)
}
ServletOutputStream out = response.getOutputStream(); // 好像是獲取輸出流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // 編碼器
encoder.encode(bi); // 對(duì)圖片進(jìn)行編碼
out.flush(); // 輸出到客戶端
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
3. 創(chuàng)建注冊(cè)控制器——RegistServlet
package com.phome.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 注冊(cè)控制器
* @author ZuoYi
*
*/
public class RegistServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 從session中獲取注冊(cè)隨機(jī)驗(yàn)證碼
HttpSession session = req.getSession();
String randomString = (String)session.getAttribute("randomString");
// 獲取用戶輸入驗(yàn)證碼
String inputRandomString = req.getParameter("randomStr");
// 判斷驗(yàn)證碼通過,模擬進(jìn)行注冊(cè)
if (randomString.equals(inputRandomString)) {
req.setAttribute("resinfo", "恭喜!注冊(cè)成功!");
} else {
req.setAttribute("resinfo", "驗(yàn)證碼輸入有誤,請(qǐng)檢查后重新進(jìn)行注冊(cè)!");
}
// 注冊(cè)成功或者失敗,都跳轉(zhuǎn)到result.jsp頁面,查看注冊(cè)結(jié)果。。。
req.getRequestDispatcher("result.jsp").forward(req, resp);
}
}
4. 配置servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>simg</display-name> <!-- 配置用戶注冊(cè)servlet --> <servlet> <servlet-name>registservlet</servlet-name> <servlet-class>com.phome.servlet.RegistServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>registservlet</servlet-name> <url-pattern>/regist.action</url-pattern> </servlet-mapping> <!-- 配置圖形驗(yàn)證碼servlet --> <servlet> <servlet-name>verifyimg</servlet-name> <servlet-class>com.phome.servlet.VerifyImgServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>verifyimg</servlet-name> <url-pattern>/verifyimg.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
5. 創(chuàng)建注冊(cè)視圖測(cè)試頁面——regist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" >
-->
</head>
<body>
<form action="${pageContext.request.contextPath}/regist.action" method="post">
用戶名:<input type="text" name="username"/>
<br />
密碼:<input type="text" name="password"/>
<br />
請(qǐng)輸入驗(yàn)證碼進(jìn)行注冊(cè):
<img src="${pageContext.request.contextPath }/verifyimg.action"/>
<input type="text" name="randomStr"/>
<br />
<input type="submit" value="regist"/>
</form>
</body>
</html>
5.1 創(chuàng)建注冊(cè)結(jié)果頁面——result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" >
-->
</head>
<body>
${requestScope.resinfo }
</body>
</html>
6.測(cè)試
(1)a.打開瀏覽器,輸入測(cè)試地址:http://localhost:8080/java_servlet_verifyimg;出現(xiàn)如下圖所示頁面

b.輸入注冊(cè)賬號(hào)、密碼和驗(yàn)證碼后點(diǎn)擊regist提交

c.測(cè)試結(jié)果,跳轉(zhuǎn)會(huì)注冊(cè)頁面,提示注冊(cè)成功

(2)打開注冊(cè)頁面

輸入錯(cuò)誤注冊(cè)碼

測(cè)試結(jié)果頁面

over!
更多關(guān)于驗(yàn)證碼的文章請(qǐng)點(diǎn)擊查看:《java驗(yàn)證碼》
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
文章名稱:javaweb開發(fā)之servlet圖形驗(yàn)證碼功能的實(shí)現(xiàn)
分享地址:http://www.chinadenli.net/article2/jdhioc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、、小程序開發(fā)、做網(wǎng)站、網(wǎng)站導(dǎo)航、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)