驗證碼編程
㈠ 如何用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>