1. 驗證碼部分的java代碼怎麼寫
package com.bbs.servlet;
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.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
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 Image extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width = 60, 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));
// 隨機產生155條干擾線,使圖象中的認證碼不易被其它程序探測到
g.setColor(getRandColor(180, 200));
for (int i = 0; i < 155; 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);
}
// 取隨機產生的認證碼(4位數字)
String sRand =setRandValue(request);
if(sRand!=null)
for (int i = 0; i < sRand.length(); i++) {
g.setColor(new Color(20 + random.nextInt(200), 20 + random
.nextInt(200), 20 + random.nextInt(200)));
// 調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
g.drawString(sRand.charAt(i) + "", 13 * i + 6, 16);
}
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
// 圖象生效
g.dispose();
// 輸出圖象到頁面
// ImageIO.write(image, "JPG", response.getOutputStream());
out.flush();
out.close();
}
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);
}
//48-57對應0-9;65-90對應A-Z;97-122對應a-z;
String setRandValue(HttpServletRequest request) {
Random random = new Random();
String sRand = "";
//這里是生成驗證碼的位數
for (int i = 0; i < 4; i++) {
char c = 0;
int k = random.nextInt(3);
switch (k) {
case 0:
c = (char) (random.nextInt(10) + 48);
break;
case 1:
c = (char) (random.nextInt(26) + 65);
break;
case 2:
c = (char) (random.nextInt(26) + 97);
}
sRand += c;
}
request.getSession().setAttribute("rands", sRand);
return sRand;
}
}
2. 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, Map<String, String> params) { //構造HttpClient的實例 HttpClient httpClient = new HttpClient(); //創建POST方法的實例 PostMethod postMethod = new PostMethod(url); //設置請求頭信息 postMethod.setRequestHeader("Connection", "close"); //添加參數 for (Map.Entry<String, 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, Map<String, 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提交地址"; Map<String, String> params = new HashMap<String, 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編碼。
3. java 登陸時的驗證碼怎麼做
後台寫一個生成圖片隨機的代碼,生成圖片給前台。切換圖片的時候,使用ajax獲取圖片數據就行。
附上生成圖片的代碼
public class ValidateCode {
private int width=180;
private int height=60;
private int codeCount = 4;
private int x = 0;
private int codeY;
private String Code;
private BufferedImage buffImg;
static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private int fontHeight;
public ValidateCode() {
x = width / (codeCount + 2);
fontHeight = height - 2;
codeY = height - 4;
CreateCode();
}
public void CreateCode(){
// 定義圖像buffer
BufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 創建一個隨機數生成器類
Random random = new Random();
// 將圖像填充為白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 創建字體,字體的大小應該根據圖片的高度來定。
Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
// 設置字體。
g.setFont(font);
// 畫邊框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
// randomCode用於保存隨機產生的驗證碼,以便用戶登錄後進行驗證。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// 隨機產生codeCount數字的驗證碼。
for (int i = 0; i < codeCount; i++) {
// 得到隨機產生的驗證碼數字。
String strRand = String.valueOf(codeSequence[random.nextInt(62)]);
// 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數字的顏色值都將不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用隨機產生的顏色將驗證碼繪制到圖像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i ) * x+20, codeY);
// 將產生的四個隨機數組合在一起。
randomCode.append(strRand);
}
this.Code=randomCode.toString().toUpperCase();
this.buffImg=buffImg;
}
public String getCode() {
return Code;
}
public void setCode(String code) {
Code = code;
}
public BufferedImage getBuffImg() {
return buffImg;
}
public void setBuffImg(BufferedImage buffImg) {
this.buffImg = buffImg;
}
}
4. java怎麼編寫混合驗證碼(控制台輸出就可以)
importjava.util.Random;
{
//驗證碼圖片中可以出現的字元集,可以根據需要修改
privatestaticcharmapTable[]={
'a','b','c','d','e','f',
'g','h','i','j','k','l',
'm','n','o','p','q','r',
's','t','u','v','w','x',
'y','z','0','1','2','3',
'4','5','6','7','8','9'
};
staticRandomsc=newRandom();
publicstaticvoidmain(String[]args)
{
System.out.println("混合驗證碼:");
for(inti=0;i<4;i++)
{
System.out.print(mapTable[sc.nextInt(mapTable.length)]);
}
}
}
5. 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.a
6. spring框架的java登錄驗證碼怎麼寫
可以參考下下面的代碼,這個代碼是servlet生成的,稍微修改下就能用的
packageservlet;
importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics;
importjava.awt.image.BufferedImage;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;
importjavax.imageio.ImageIO;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
{
publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
BufferedImageimage=newBufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
Graphicsg=image.getGraphics();
Randomr=newRandom();
g.setColor(newColor(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.fillRect(0,0,100,30);
g.setColor(newColor(255,255,255));
g.setFont(newFont(null,Font.BOLD,24));
Stringcode=getCode();
HttpSessionsession=request.getSession();
session.setAttribute("textcode",code);
g.drawString(code,10,25);
response.setContentType("image/jpeg");
OutputStreamos=response.getOutputStream();
ImageIO.write(image,"jpeg",os);
os.close();
}
//隨機生成驗證碼字元串的類
publicstaticStringgetCode(){
char[]letters={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z'};
Stringcode="";
boolean[]bool=newboolean[letters.length];
for(inti=0;i<5;i++){
intnum;
do{
num=(int)(Math.random()*(letters.length));
}while(bool[num]);
code+=letters[num];
bool[num]=true;
}
returncode.toUpperCase();
}
}
7. 怎樣用java實現驗證碼
package com.servlet;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.imageio.ImageIO;
public class PictureCheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
public PictureCheckCode() {
super();
}
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
super.init();
}
/*該方法主要作用是獲得隨機生成的顏色*/
public Color getRandColor(int s,int e){
Random random=new Random ();
if(s>255) s=255;
if(e>255) e=255;
int r,g,b;
r=s+random.nextInt(e-s); //隨機生成RGB顏色中的r值
g=s+random.nextInt(e-s); //隨機生成RGB顏色中的g值
b=s+random.nextInt(e-s); //隨機生成RGB顏色中的b值
return new Color(r,g,b);
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設置不緩存圖片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//指定生成的響應圖片,一定不能缺少這句話,否則錯誤.
response.setContentType("image/jpeg");
int width=86,height=22; //指定生成驗證碼的寬度和高度
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //創建BufferedImage對象,其作用相當於一圖片
Graphics g=image.getGraphics(); //創建Graphics對象,其作用相當於畫筆
Graphics2D g2d=(Graphics2D)g; //創建Grapchics2D對象
Random random=new Random();
Font mfont=new Font("楷體",Font.BOLD,16); //定義字體樣式
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height); //繪制背景
g.setFont(mfont); //設置字體
g.setColor(getRandColor(180,200));
//繪制100條顏色和位置全部為隨機產生的線條,該線條為2f
for(int i=0;i<100;i++){
int x=random.nextInt(width-1);
int y=random.nextInt(height-1);
int x1=random.nextInt(6)+1;
int y1=random.nextInt(12)+1;
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL); //定製線條樣式
Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
g2d.setStroke(bs);
g2d.draw(line); //繪制直線
}
//輸出由英文,數字,和中文隨機組成的驗證文字,具體的組合方式根據生成隨機數確定。
String sRand="";
String ctmp="";
int itmp=0;
//制定輸出的驗證碼為四位
for(int i=0;i<4;i++){
switch(random.nextInt(3)){
case 1: //生成A-Z的字母
itmp=random.nextInt(26)+65;
ctmp=String.valueOf((char)itmp);
break;
case 2: //生成漢字
String[] rBase={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
//生成第一位區碼
int r1=random.nextInt(3)+11;
String str_r1=rBase[r1];
//生成第二位區碼
int r2;
if(r1==13){
r2=random.nextInt(7);
}else{
r2=random.nextInt(16);
}
String str_r2=rBase[r2];
//生成第一位位碼
int r3=random.nextInt(6)+10;
String str_r3=rBase[r3];
//生成第二位位碼
int r4;
if(r3==10){
r4=random.nextInt(15)+1;
}else if(r3==15){
r4=random.nextInt(15);
}else{
r4=random.nextInt(16);
}
String str_r4=rBase[r4];
//將生成的機內碼轉換為漢字
byte[] bytes=new byte[2];
//將生成的區碼保存到位元組數組的第一個元素中
String str_12=str_r1+str_r2;
int tempLow=Integer.parseInt(str_12, 16);
bytes[0]=(byte) tempLow;
//將生成的位碼保存到位元組數組的第二個元素中
String str_34=str_r3+str_r4;
int tempHigh=Integer.parseInt(str_34, 16);
bytes[1]=(byte)tempHigh;
ctmp=new String(bytes);
break;
default:
itmp=random.nextInt(10)+48;
ctmp=String.valueOf((char)itmp);
break;
}
sRand+=ctmp;
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
g.setColor(color);
//將生成的隨機數進行隨機縮放並旋轉制定角度 PS.建議不要對文字進行縮放與旋轉,因為這樣圖片可能不正常顯示
/*將文字旋轉制定角度*/
Graphics2D g2d_word=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
trans.rotate((45)*3.14/180,15*i+8,7);
/*縮放文字*/
float scaleSize=random.nextFloat()+0.8f;
if(scaleSize>1f) scaleSize=1f;
trans.scale(scaleSize, scaleSize);
g2d_word.setTransform(trans);
g.drawString(ctmp, 15*i+18, 14);
}
HttpSession session=request.getSession(true);
session.setAttribute("randCheckCode", sRand);
g.dispose(); //釋放g所佔用的系統資源
ImageIO.write(image,"JPEG",response.getOutputStream()); //輸出圖片
}
}
8. 如何用Java代碼段生成四位數字加字母的驗證碼
不知道你問的是不是生成這種圖片驗證碼?如果只要一個隨機四位數 那這行代碼就夠了(new Random().nextInt(9000) + 1000;),如果是生成頁面圖片驗證碼就是下面的了: //設定 響應模式 resp.setContentType("image/jpeg"); // 生成令牌環數據; Integer token = new Random().nextInt(9000) + 1000; // 保存令牌環數據到session中 req.getSession().setAttribute(IMAGE_TOKEN_NAME, token); // 生成令牌環圖片 ServletOutputStream out = resp.getOutputStream(); BufferedImage img = new BufferedImage(60, 20, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); g.setColor(Color.YELLOW); g.fillRect(0, 0, img.getWidth(), img.getHeight()); g.setColor(Color.BLUE); g.setFont(new Font("", Font.BOLD, 18)); g.drawString(String.valueOf(token), 10, 16); ImageIO.write(img, "jpg", out); out.close();
下面簡單的介紹他們的功能和用途,執行效率等。每個都有各自的優缺點看你是做甚什麼方面的研究開發用。.net,是網站編程,現在很多都用這個,但是這個語言編程都有統一思路,很好掌握。窒息那個效率不是很高;php 支持跨平台,很容易學會,執行的效率很高;asp是ASP.net的前身,它比較穩定,比.net要弱一點。但是比.net好學。jsp 是網頁編程,這個學習大約一周就能搞定,不過這個得多實踐,不然的話,時間長了,就容易忘記。
我自己做的系統裡面用作驗證碼的JSP的<%@page contentType="image/jpeg;charset=utf-8"%><%@page import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" %><%@ page import="java.io.OutputStream" %><html> <body> <%! Color getRandColor(int fc,int bc) { Random rd=new Random(); if(fc>255) fc=255; if(bc>255) bc=255; int red=fc+rd.nextInt(bc-fc); int green=fc+rd.nextInt(bc-fc); int blue=fc+rd.nextInt(bc-fc); return new Color(red,green,blue); } %> <% Random r=new Random(); response.addHeader("Pragma","No-cache"); response.addHeader("Cache-Control","no-cache"); response.addDateHeader("expires",0); int width=90; int height=23; BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics gc=pic.getGraphics(); gc.setColor(getRandColor(200,250)); gc.fillRect(0,0,width,height); String[] rNum ={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f", "g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w", "x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N", "O","P","Q","R","S","T","U","V","W","X","Y","Z"}; int[] style = {Font.PLAIN,Font.BOLD,Font.ITALIC,Font.PLAIN+Font.BOLD, Font.BOLD+Font.ITALIC,Font.PLAIN+Font.ITALIC,Font.PLAIN+Font.BOLD+Font.ITALIC}; gc.setColor(Color.WHITE); gc.drawLine(0,30,90,10); gc.setColor(getRandColor(160,200)); for (int i=0;i<50;i++) { int x = r.nextInt(width); int y = r.nextInt(height); int xl = r.nextInt(10); int yl = r.nextInt(10); gc.drawLine(x,y,x+xl,y+yl); } gc.setColor(getRandColor(60,150)); String rt = ""; for(int i=0;i<4;i++){ String temp = rNum[r.nextInt(62)]; rt = rt+temp; gc.setFont(new Font("Times New Roman",style[r.nextInt(7)],15)); gc.drawString(temp,5+i*15+r.nextInt(10),10+r.nextInt(10)); } gc.dispose(); session.setAttribute("randNum",rt); OutputStream os=response.getOutputStream(); ImageIO.write(pic,"JPEG",os); System.out.println("當前驗證碼為:"+session.getAttribute("randNum")); os.flush(); os.close(); os=null; response.flushBuffer(); out.clear(); out = pageContext.pushBody(); %> </body></html>
9. 如何在java中生成驗證碼在頁面生成
以下是我寫的生成的圖片驗證碼
//調用驗證碼生成並把驗證碼返回頁面
Map<String,BufferedImage>imageMap=ImageUtil.createImage();
Stringcode=imageMap.keySet().iterator().next();
session.setAttribute("imageCode",code);
BufferedImageimage=imageMap.get(code);
response.setContentType("image/jpeg");
OutputStreamops=response.getOutputStream();
ImageIO.write(image,"jpeg",ops);
ops.close();
//生成驗證碼工具類
publicfinalclassImageUtil{
privatestaticfinalchar[]chars={'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T','U','V','W',
'X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
privatestaticfinalintSIZE=4;
privatestaticfinalintLINES=5;
privatestaticfinalintWIDTH=80;
privatestaticfinalintHEIGHT=40;
privatestaticfinalintFONT_SIZE=30;
publicstaticMap<String,BufferedImage>createImage(){
StringBuffersb=newStringBuffer();
BufferedImageimage=newBufferedImage(WIDTH,HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphicsgraphic=image.getGraphics();
graphic.setColor(Color.LIGHT_GRAY);
graphic.fillRect(0,0,WIDTH,HEIGHT);
Randomran=newRandom();
//畫隨機字元
for(inti=1;i<=SIZE;i++){
intr=ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(newFont(null,Font.BOLD+Font.ITALIC,FONT_SIZE));
graphic.drawString(chars[r]+"",(i-1)*WIDTH/SIZE,HEIGHT/2);
sb.append(chars[r]);
}
//畫干擾線
for(inti=1;i<=LINES;i++){
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH),ran.nextInt(HEIGHT),
ran.nextInt(WIDTH),ran.nextInt(HEIGHT));
}
Map<String,BufferedImage>map=newHashMap<String,BufferedImage>();
map.put(sb.toString(),image);
returnmap;
}
(){
Randomran=newRandom();
Colorcolor=newColor(ran.nextInt(256),ran.nextInt(256),ran.nextInt(256));
returncolor;
}
(BufferedImageimage)
throwsIOException{
ByteArrayOutputStreambos=newByteArrayOutputStream();
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
byte[]imageBts=bos.toByteArray();
InputStreamin=newByteArrayInputStream(imageBts);
returnin;
}
}
10. 怎麼用java實現驗證碼
1、網上有JS插件啊,這個用java實現的話還是比較麻煩哦,需要java調用畫圖。我有一個寫好的例子,是java和servlet做的。
2、親們,這個驗證碼我做了很久才弄出來的,希望大家別介意我收費哦!