servlet awt隨機圖片驗證碼

劍握在手發表於2013-11-30
package rd.test;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
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 Test1 extends HttpServlet {

	public static final int WIDTH = 120;
	public static final int HEIGHT = 35;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();
		
		//1,設定背景色
		setBackGround(g);
		
		//2,設定邊框
		setBorder(g);
		
		//3,畫干擾線
		drowRandomLine(g);
		
		//4,寫隨機數
		//drawRandomNum(g);
		String random = drawRandomNum2d((Graphics2D)g);//驗證相關
          request.getSession().setAttribute("checkcode",random);//驗證相關		
//5,圖形寫給瀏覽器 response.setContentType("image/jpeg"); //控制瀏覽器不要快取隨機驗證碼圖片,讓它每次都更新 response.setDateHeader("expries", -1); response.setHeader("Cache-Control","no-cache"); response.setHeader("Pragma","no-cache"); ImageIO.write(image, "jpg", response.getOutputStream()); } private void drowRandomLine(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.GRAY); for(int i = 0;i<5;i++) { int x1 = new Random().nextInt(WIDTH-2)+2; int y1 = new Random().nextInt(HEIGHT-2)+2; int x2 = new Random().nextInt(WIDTH-2)+2; int y2 = new Random().nextInt(HEIGHT-2)+2; g.drawLine(x1, y1, x2, y2); } } private String drawRandomNum2d(Graphics2D g) { // TODO Auto-generated method stub g.setColor(Color.RED); g.setFont(new Font("宋體",Font.BOLD,20)); //[\u4e00-\u9fa5] String base = "一二三四五六七八九十百千萬兆億啊我餓依無餘";           StringBuffer sb = new StringBuffer();//驗證相關
int x = 5; for(int i = 0;i<4;i++) { int degree = new Random().nextInt()%30; String ch = "" + base.charAt(new Random().nextInt(base.length())); sb.append(ch);//驗證相關
              g.rotate(degree*Math.PI/180, x, 25);//設定旋轉幅度 g.drawString(ch, x, 25); g.rotate(-degree*Math.PI/180, x, 25);//轉回去 x+=30; }
          return sb.toString(); } private void drawRandomNum(Graphics g) { g.setColor(Color.RED); g.setFont(new Font("宋體",Font.BOLD,20)); //[\u4e00-\u9fa5] String base = "一二三四五六七八九十百千萬兆億啊我餓依無餘"; int x = 5; for(int i = 0;i<4;i++) { String ch = "" + base.charAt(new Random().nextInt(base.length())); g.drawString(ch, x, 20); x+=30; } } private void setBorder(Graphics g) { g.setColor(Color.BLUE); g.drawRect(1, 1, WIDTH-2, HEIGHT-2); } private void setBackGround(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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%>">
    
    <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">
    -->
    
    <script type="text/javascript">
        function changeImg(img){
            img.src = img.src + "?" + new Date().getTime();
        }
    </script>
    
  </head>
  
  <body>
  
      <form action="/web/servlet/check" method="post">
          使用者名稱:<input type="text" name="username">
          密碼 :<input type="password" name="password"><br/><br/>
          驗證碼:<input type = "text" name="checkcode">
          <img src="http://localhost:8080/random/servlet/Test1" onclick="changeImg(this)"/>
          <input type="submit" value="註冊">
      </form> 
  </body>
</html>

 

check:

 

request.setCharacterEncoding("UTF-8");

String c_checkcode = request.getParameter("checkcode");

String s_checkcode = request.getSession().getAttribut("checkcode");

if(c_checkcode!=null && s_checkcode!=null && c_checkcode.equals(s_checkcode)){

  System.out.println("處理註冊請求“);

}else{

  System.out.println("驗證碼錯誤");

}

相關文章