手心創建一個簡單的頁面來顯示所創建的驗證碼
<body> <form action="loginName.mvc" method="post"> 用戶名:<input type="text" name="name" id="name"/><br/> 密碼:<input type="password" name="password" id="password"/><br/> 驗證碼1:<a href="javascript:changePicture1();" title='看不清楚,換個圖片'><img id="checkcode1" src=""><a href="javascript:changePicture1();" class="login-text03" title='看不清楚,換個圖片'>看不清楚,換個圖片</a><br/> 驗證碼2:<a href="javascript:changePicture2();" title='看不清楚,換個圖片'><img id="checkcode2" src=""><a href="javascript:changePicture2();" class="login-text03" title='看不清楚,換個圖片'>看不清楚,換個圖片</a><br/> 驗證碼3:<a href="javascript:changePicture3();" title='看不清楚,換個圖片'><img id="checkcode3" src=""><a href="javascript:changePicture3();" class="login-text03" title='看不清楚,換個圖片'>看不清楚,換個圖片</a> <span id="spantext"></span><br/> <!-- <input type="button" value="登錄" onclick="loginPerson()"/>--> <input type="submit" value="登錄"/> </form> </body> <script language="javascript"> window.onload=function(){ changePicture1(); changePicture2(); changePicture3(); }; function changePicture1(){ $("#checkcode1").attr("src","servlet/CheckCode?code="+Math.random()); } function changePicture2(){ /* var arry=["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"]; var len=arry.length; var code=""; for(i=0;i<=4;i++){ var index=Math.floor(Math.random()*len); code+=arry[index]; } */ //alert(code); $("#checkcode2").attr("src","servlet/ImageServlet?code="+Math.random()); } function changePicture3(){ $("#checkcode3").attr("src","servlet/graphicsImage?code="+Math.random()); } function loginPerson(){ var name=document.getElementById("name").value; var password=document.getElementById("password").value; if(name==""||password==""){ alert("賬戶名或密碼不能為空"); $("#spantext").html("賬戶名或密碼不能為空"); }else{ $.ajax({ type : "post", url : "./loginName.mvc?name="+name+"&password="+password, success : function(data){ alert(data); var obj=eval("("+data+")"); var message=obj.code; //var name=obj.name; //var password=obj.password; alert(message); //alert(name); //alert(password); }, error : function(data){ $("#spantext").html("網絡錯誤"); } }); } } </script>
在這里寫有三個生成驗證碼的類,其實他們的本質是一樣的 ,都是類似的

package com.chinasoft.ssm.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.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CheckCode extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); // 圖片的內存映像 BufferedImage image = new BufferedImage(60, 20,BufferedImage.TYPE_INT_BGR); // 獲取畫筆對象 Graphics g = image.getGraphics(); //隨機變換圖片的顏色 Random r = new Random(); g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255))); //開始繪制圖片 g.fillRect(0, 0, 60, 20); //將畫筆顏色清零 g.setColor(new Color(0,0,0)); Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 16); g.setFont(font); String number = String.valueOf(r.nextInt(99999)); HttpSession session = request.getSession(); session.setAttribute("number", number); g.drawString(number, 5, 15); g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255))); //壓縮jpeg格式轉換為輸出流的形式 OutputStream os = response.getOutputStream(); //把輸出流對象中的圖像信息編碼 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); //向創建對象時指定的輸出流輸出 encoder.encode(image); os.flush(); os.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }

package com.chinasoft.ssm.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.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 ImageServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String ch1= (String) request.getParameter("code"); System.out.println(ch1); response.setContentType("image/jpeg"); // 圖片的內存映像 BufferedImage bi=new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB); //獲得畫筆對象 Graphics g=bi.getGraphics(); //圖片的顏色選擇 Color c=new Color(200,150,255); g.setColor(c); //開始繪制圖片 g.fillRect(0, 0, 68, 22); char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); Random r=new Random(); int len=ch.length; int index; StringBuffer sb=new StringBuffer(); for(int i=0;i<4;i++) { //獲取一個隨機數 index=r.nextInt(len); //給字體設置顏色 Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 16); g.setFont(font); g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255))); //將所有選擇的字體繪畫出來 g.drawString(ch[index]+"",(i*15)+3, 18); //將隨機生成的驗證碼添加到可變字符sb中去 sb.append(ch[index]); } //將生成的驗證碼對象保存到piccode對應的value中去 //request.getSession().setAttribute("piccode", sb.toString()); //使用給定的支持格式將圖像BufferedImage的bi對象寫入到響應輸出流當中 //ImageIO.write(bi, "JPG", response.getOutputStream()); OutputStream os = response.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); //向創建對象時指定的輸出流輸出 encoder.encode(bi); os.flush(); os.close(); } }

package com.chinasoft.ssm.servlet; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; 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; public class graphicsImage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { char[] strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray(); BufferedImage bi = new BufferedImage(150,40,BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D)bi.getGraphics(); Random num=new Random(); Color color ; int len = strs.length; g.setColor(Color.WHITE); g.fillRect(0,0,150,40); // 隨機畫干擾的蛋蛋 for(int i=0;i<15;i++){ color =new Color(150,100, 250); g.setColor(color); // 畫蛋蛋,有蛋的生活才精彩 g.drawOval(num.nextInt(150), num.nextInt(40), 5+num.nextInt(10), 5+num.nextInt(10)); color = null; } Font font = new Font("Verdana", Font.ITALIC|Font.BOLD, 28); g.setFont(font); /* 畫字符串 */ for(int i=0;i<6;i++) { int index=num.nextInt(len); // 指定透明度 AlphaComposite ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f); g.setComposite(ac3); // 對每個字符都用隨機顏色 color = new Color(20 + num.nextInt(110), 20 + num.nextInt(110), 20 + num.nextInt(110)); g.setColor(color); g.drawString(strs[index]+"",(i*15)+40, 40-4); color = null; ac3 = null; } ImageIO.write(bi, "png", response.getOutputStream()); } public void init() throws ServletException { // Put your code here } }