本文目錄一覽:
用java怎麼製作驗證碼
原理:
1.隨機生成4個數字 用到了Random類
2.對這4個數字設置字體格式 用 setFont方法
3.改變字體顏色用setColor 然後隨機生成顏色
代碼如下
package s1;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class GetImage extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 發送圖片不能夠添加這2行代碼
// response.setContentType(“text/html;charset=UTF-8”);
// request.setCharacterEncoding(“UTF-8”);
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(1, 1, width-2, height-2);
g.setFont(new Font(“宋體”,Font.BOLD,30));
Random random=new Random();
// 填充的字元串
String str=”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
//緩存生成的驗證碼
StringBuffer stringbuffer=new StringBuffer();
//隨機生成驗證碼的顏色和字元
for(int i=0;i4;i++)
{ //設置隨機顏色
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
int index=random.nextInt(62);//這裡的62就是從填充字元段中隨意選取一個位置
String str1=str.substring(index,index+1);
g.drawString(str1, 20*i, 30);//x,y數值設置太小會顯示不出來
stringbuffer.append(str1);
}
//將生成的驗證碼存到伺服器
request.getSession().setAttribute(“checkcode”, stringbuffer.toString());//key和value
//將圖片發送給瀏覽器
ImageIO.write(image, “jpg”, response.getOutputStream());
}
}
用戶登錄界面代碼
package s1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);// 設置伺服器發送給瀏覽器的編碼方式
request.setCharacterEncoding(“UTF-8”); // 客戶端向伺服器提交的數據的解碼方式
// 獲得用戶提交的數據
String checkcode = request.getParameter(“checkcode”);
System.out.println(checkcode);
// 判斷輸入的驗證碼是不是符合
HttpSession session = request.getSession();// session是存放數據的地方
String str = (String) session.getAttribute(“checkcode”);
if (str != null) {
if (checkcode.compareToIgnoreCase(str) == 0) // 驗證碼忽略大小寫
response.getWriter().println(“驗證碼輸入正確”);
else
response.getWriter().println(“驗證碼輸入錯誤”);
}
else response.getWriter().println(“驗證碼失效”);
// 使用完的驗證碼信息要刪除,返回原頁面再輸一次,驗證碼就失效了
session.removeAttribute(“checkcode”);
}
}
java如何實現發送簡訊驗證碼功能?
1、創建一個Http的模擬請求工具類,然後寫一個POST方法或者GET方法
/** * 文件說明 * @Description:擴展說明 * @Copyright: XXXX dreamtech.com.cn Inc. All right reserved * @Version: V6.0 */package com.demo.util; import java.io.IOException;import java.util.Map; import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.SimpleHttpConnectionManager;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod; /** * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser: feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX * @Version:V6.0 */public class HttpRequestUtil { /** * HttpClient 模擬POST請求 * 方法說明 * @Discription:擴展說明 * @param url * @param params * @return String * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser:feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX */ public static String postRequest(String url, MapString, String params) { //構造HttpClient的實例 HttpClient httpClient = new HttpClient(); //創建POST方法的實例 PostMethod postMethod = new PostMethod(url); //設置請求頭信息 postMethod.setRequestHeader(“Connection”, “close”); //添加參數 for (Map.EntryString, String entry : params.entrySet()) { postMethod.addParameter(entry.getKey(), entry.getValue()); } //使用系統提供的默認的恢復策略,設置請求重試處理,用的是默認的重試處理:請求三次 httpClient.getParams().setBooleanParameter(“http.protocol.expect-continue”, false); //接收處理結果 String result = null; try { //執行Http Post請求 httpClient.executeMethod(postMethod); //返回處理結果 result = postMethod.getResponseBodyAsString(); } catch (HttpException e) { // 發生致命的異常,可能是協議不對或者返回的內容有問題 System.out.println(“請檢查輸入的URL!”); e.printStackTrace(); } catch (IOException e) { // 發生網路異常 System.out.println(“發生網路異常!”); e.printStackTrace(); } finally { //釋放鏈接 postMethod.releaseConnection(); //關閉HttpClient實例 if (httpClient != null) { ((SimpleHttpConnectionManager) httpClient.getHttpConnectionManager()).shutdown(); httpClient = null; } } return result; } /** * HttpClient 模擬GET請求 * 方法說明 * @Discription:擴展說明 * @param url * @param params * @return String * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser:feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX */ public static String getRequest(String url, MapString, String params) { //構造HttpClient實例 HttpClient client = new HttpClient(); //拼接參數 String paramStr = “”; for (String key : params.keySet()) { paramStr = paramStr + “” + key + “=” + params.get(key); } paramStr = paramStr.substring(1); //創建GET方法的實例 GetMethod method = new GetMethod(url + “?” + paramStr); //接收返回結果 String result = null; try { //執行HTTP GET方法請求 client.executeMethod(method); //返回處理結果 result = method.getResponseBodyAsString(); } catch (HttpException e) { // 發生致命的異常,可能是協議不對或者返回的內容有問題 System.out.println(“請檢查輸入的URL!”); e.printStackTrace(); } catch (IOException e) { // 發生網路異常 System.out.println(“發生網路異常!”); e.printStackTrace(); } finally { //釋放鏈接 method.releaseConnection(); //關閉HttpClient實例 if (client != null) { ((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown(); client = null; } } return result; }}
2、在創建一個類,生成驗證碼,然後傳遞相應的參數(不同的簡訊平台介面會有不同的參數要求,這個一般簡訊平台提供的介面文檔中都會有的,直接看文檔然後按要求來即可)
/** * 文件說明 * @Description:擴展說明 * @Copyright: XXXX dreamtech.com.cn Inc. All right reserved * @Version: V6.0 */package com.demo.util; import java.net.URLEncoder;import java.util.HashMap;import java.util.Map; /** * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser: feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX * @Version:V6.0 */public class SendMsgUtil { /** * 發送簡訊消息 * 方法說明 * @Discription:擴展說明 * @param phones * @param content * @return * @return String * @Author: feizi * @Date: 2015年4月17日 下午7:18:08 * @ModifyUser:feizi * @ModifyDate: 2015年4月17日 下午7:18:08 */ @SuppressWarnings(“deprecation”) public static String sendMsg(String phones,String content){ //簡訊介面URL提交地址 String url = “簡訊介面URL提交地址”; MapString, String params = new HashMapString, String(); params.put(“zh”, “用戶賬號”); params.put(“mm”, “用戶密碼”); params.put(“dxlbid”, “簡訊類別編號”); params.put(“extno”, “擴展編號”); //手機號碼,多個號碼使用英文逗號進行分割 params.put(“hm”, phones); //將簡訊內容進行URLEncoder編碼 params.put(“nr”, URLEncoder.encode(content)); return HttpRequestUtil.getRequest(url, params); } /** * 隨機生成6位隨機驗證碼 * 方法說明 * @Discription:擴展說明 * @return * @return String * @Author: feizi * @Date: 2015年4月17日 下午7:19:02 * @ModifyUser:feizi * @ModifyDate: 2015年4月17日 下午7:19:02 */ public static String createRandomVcode(){ //驗證碼 String vcode = “”; for (int i = 0; i 6; i++) { vcode = vcode + (int)(Math.random() * 9); } return vcode; } /** * 測試 * 方法說明 * @Discription:擴展說明 * @param args * @return void * @Author: feizi * @Date: XXXX年XX月XX日 XX:XX:XX * @ModifyUser:feizi * @ModifyDate: XXXX年XX月XX日 XX:XX:XX */ public static void main(String[] args) {// System.out.println(SendMsgUtil.createRandomVcode());// System.out.println(“ecb=12”.substring(1)); System.out.println(sendMsg(“18123456789,15123456789”, “尊敬的用戶,您的驗證碼為” + SendMsgUtil.createRandomVcode() + “,有效期為60秒,如有疑慮請詳詢XXX-XXX-XXXX【XXX中心】”)); }
然後執行一下,一般的情況下參數傳遞正確,按照介面文檔的規範來操作的話,都會發送成功的,手機都能收到驗證碼的,然後可能會出現的問題就是:發送的簡訊內容有可能會出現中文亂碼,然後就會發送不成功,按照簡訊平台的要求進行相應的編碼即可。一般都會是UTF-8編碼。
Java如何實現驗證碼驗證功能
Java如何實現驗證碼驗證功能呢?日常生活中,驗證碼隨處可見,他可以在一定程度上保護賬號安全,那麼他是怎麼實現的呢?
Java實現驗證碼驗證功能其實非常簡單:用到了一個Graphics類在畫板上繪製字母,隨機選取一定數量的字母隨機生成,然後在畫板上隨機生成幾條幹擾線。
首先,寫一個驗證碼生成幫助類,用來繪製隨機字母:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public final class GraphicHelper {
/**
* 以字元串形式返回生成的驗證碼,同時輸出一個圖片
*
* @param width
* 圖片的寬度
* @param height
* 圖片的高度
* @param imgType
* 圖片的類型
* @param output
* 圖片的輸出流(圖片將輸出到這個流中)
* @return 返回所生成的驗證碼(字元串)
*/
public static String create(final int width, final int height, final String imgType, OutputStream output) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.getColor(“F8F8F8”));
graphic.fillRect(0, 0, width, height);
Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
Color.CYAN };
// 在 “畫板”上生成干擾線條 ( 50 是線條個數)
for (int i = 0; i 50; i++) {
graphic.setColor(colors[random.nextInt(colors.length)]);
final int x = random.nextInt(width);
final int y = random.nextInt(height);
final int w = random.nextInt(20);
final int h = random.nextInt(20);
final int signA = random.nextBoolean() ? 1 : -1;
final int signB = random.nextBoolean() ? 1 : -1;
graphic.drawLine(x, y, x + w * signA, y + h * signB);
}
// 在 “畫板”上繪製字母
graphic.setFont(new Font(“Comic Sans MS”, Font.BOLD, 30));
for (int i = 0; i 6; i++) {
final int temp = random.nextInt(26) + 97;
String s = String.valueOf((char) temp);
sb.append(s);
graphic.setColor(colors[random.nextInt(colors.length)]);
graphic.drawString(s, i * (width / 6), height – (height / 3));
}
graphic.dispose();
try {
ImageIO.write(image, imgType, output);
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
接著,創建一個servlet,用來固定圖片大小,以及處理驗證碼的使用場景,以及捕獲頁面生成的驗證碼(捕獲到的二維碼與用戶輸入的驗證碼一致才能通過)。
import java.io.OutputStream;
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;
@WebServlet(urlPatterns = “/verify/regist.do” )
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 3398560501558431737L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 獲得 當前請求 對應的 會話對象
HttpSession session = request.getSession();
// 從請求中獲得 URI ( 統一資源標識符 )
String uri = request.getRequestURI();
System.out.println(“hello : ” + uri);
final int width = 180; // 圖片寬度
final int height = 40; // 圖片高度
final String imgType = “jpeg”; // 指定圖片格式 (不是指MIME類型)
final OutputStream output = response.getOutputStream(); // 獲得可以向客戶端返回圖片的輸出流
// (位元組流)
// 創建驗證碼圖片並返回圖片上的字元串
String code = GraphicHelper.create(width, height, imgType, output);
System.out.println(“驗證碼內容: ” + code);
// 建立 uri 和 相應的 驗證碼 的關聯 ( 存儲到當前會話對象的屬性中 )
session.setAttribute(uri, code);
System.out.println(session.getAttribute(uri));
}
}
接著寫一個HTML註冊頁面用來檢驗一下:
html
head
meta charset=”UTF-8″
title註冊/title
link rel=”stylesheet” href=”styles/general.css”
link rel=”stylesheet” href=”styles/cell.css”
link rel=”stylesheet” href=”styles/form.css”
script type=”text/javascript” src=”js/ref.js”/script
style type=”text/css”
.logo-container {
margin-top: 50px ;
}
.logo-container img {
width: 100px ;
}
.message-container {
height: 80px ;
}
.link-container {
height: 40px ;
line-height: 40px ;
}
.link-container a {
text-decoration: none ;
}
/style
/head
body
div class=”container form-container”
form action=”/wendao/regist.do” method=”post”
div class=”form” !– 註冊表單開始 —
div class=”form-row”
span class=”cell-1″
i class=”fa fa-user”/i
/span
span class=”cell-11″ style=”text-align: left;”
input type=”text” name=”username” placeholder=”請輸入用戶名”
/span
/div
div class=”form-row”
span class=”cell-1″
i class=”fa fa-key”/i
/span
span class=”cell-11″ style=”text-align: left;”
input type=”password” name=”password” placeholder=”請輸入密碼”
/span
/div
div class=”form-row”
span class=”cell-1″
i class=”fa fa-keyboard-o”/i
/span
span class=”cell-11″ style=”text-align: left;”
input type=”password” name=”confirm” placeholder=”請確認密碼”
/span
/div
div class=”form-row”
span class=”cell-7″
input type=”text” name=”verifyCode” placeholder=”請輸入驗證碼”
/span
span class=”cell-5″ style=”text-align: center;”
img src=”/demo/verify/regist.do” onclick=”myRefersh(this)”
/span
/div
div class=”form-row” style=”border: none;”
span class=”cell-6″ style=”text-align: left”
input type=”reset” value=”重置”
/span
span class=”cell-6″ style=”text-align:right;”
input type=”submit” value=”註冊”
/span
/div
/div !– 註冊表單結束 —
/form
/div
/body
/html
效果如下圖:
在控制台接收到的圖片中驗證碼的變化如下:
當點擊刷新頁面的時候,驗證碼也會隨著變化,但我們看不清驗證碼時,只要點擊驗證碼就會刷新,這樣局部的刷新可以用JavaScript來實現。
在img
src=”/demo/verify/regist.do”中,添加一個問號和一串後綴數字,當刷新時讓後綴數字不斷改變,那麼形成的驗證碼也會不斷變化,我們可以採用的一種辦法是後綴數字用date代替,date獲取本機時間,時間是隨時變的,這樣就保證了刷新驗證碼可以隨時變化。
代碼如下:
function myRefersh( e ) {
const source = e.src ; // 獲得原來的 src 中的內容
//console.log( “source : ” + source ) ;
var index = source.indexOf( “?” ) ; // 從 source 中尋找 ? 第一次出現的位置 (如果不存在則返回 -1 )
//console.log( “index : ” + index ) ;
if( index -1 ) { // 如果找到了 ? 就進入內部
var s = source.substring( 0 , index ) ; // 從 source 中截取 index 之前的內容 ( index 以及 index 之後的內容都被捨棄 )
//console.log( “s : ” + s ) ;
var date = new Date(); // 創建一個 Date 對象的 一個 實例
var time = date.getTime() ; // 從 新創建的 Date 對象的實例中獲得該時間對應毫秒值
e.src = s + “?time=” + time ; // 將 加了 尾巴 的 地址 重新放入到 src 上
//console.log( e.src ) ;
} else {
var date = new Date();
e.src = source + “?time=” + date.getTime();
}
}
如回答不詳細可追問
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/276595.html