首页 > 代码库 > 两种验证码

两种验证码

这里我写了两种验证码。一种是随机生成四位数,另一种是中文字的数学题加减题。事实上就是生成图片上有点不同,别的地方一样。

html代码

<%@ 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 XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <base href=http://www.mamicode.com/"">>
struts.xml代码

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.i18n.encoding" value=http://www.mamicode.com/"UTF-8">>

java代码

package com.web.actoin;

import org.apache.struts2.ServletActionContext;

public class getyzm {
	public void getzyms(){
		System.out.println(ServletActionContext.getRequest().getSession().getAttribute("CheckCodeImageAction").toString().toUpperCase());
	}
}

package yzm;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
public class ImageResult implements Result {
    public void execute(ActionInvocation ai) throws Exception {
       ImageAction action = (ImageAction)ai.getAction();
       HttpServletResponse response = ServletActionContext.getResponse();
       response.setHeader("Cash", "no cash");
       response.setContentType(action.getContentType());
       response.setContentLength(action.getContentLength());
       response.getOutputStream().write(action.getImageBytes());
       response.getOutputStream().flush();
    }
}

以下两个能够两选一(四位数字与加减)

package yzm;
import com.opensymphony.xwork2.ActionSupport;

import java.util.Random;

import java.awt.*;

import java.awt.image.*;

import java.io.ByteArrayOutputStream;

 

import org.apache.struts2.ServletActionContext;

 

public class ImageAction extends ActionSupport {
	//
   
    private static final String SessionName = "CheckCodeImage";
    private static final Random rdm = new Random();
   
  
    private static final String[] china = new String[]{
    	"零","一","二","三","四","五","六","七","八","九"
    };
    private static final String[] fh = new String[]{
    	"加","减","乘"
    };
    
    public static Color getRandomColor(){
		return new Color(rdm.nextInt(255),rdm.nextInt(255),rdm.nextInt(255));
	}
	
	public static Color getReverseColor(Color c){
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
	}
    
    private static final Font font = new Font(Font.SANS_SERIF,Font.BOLD, 16);
    
    private String text = "";
    private byte[] bytes = null;
    private String contentType = "image/jpeg";
    public byte[] getImageBytes(){
       return this.bytes;
    }
    public String getContentType(){
       return this.contentType;
    }
    public void setContentType(String value){
       this.contentType = value;
    }
    public int getContentLength(){
       return bytes.length;
    }
    
    private void generateText(){
       String source = new String();
       int f=rdm.nextInt(ImageAction.china.length);
       int s=rdm.nextInt(ImageAction.china.length);
       int h=rdm.nextInt(ImageAction.fh.length);
       source=ImageAction.china[f]+ImageAction.fh[h]+ImageAction.china[s];
       int result=0;
       if(h==0)
    	   result=f+s;
       if(h==1)
    	   result=f-s;
       if(h==2)
    	   result=f*s;
       System.out.println("gettext:"+source);
       this.text = new String(source);
       // 锟斤拷锟斤拷Session
       ServletActionContext.getRequest().getSession().setAttribute(SessionName,result);
    }
   
    private BufferedImage createImage(){
       int width = 70;
       int height = 20;
       Color color=Color.BLACK;
		Color reverse=getReverseColor(color);
       BufferedImage image =
           new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		Graphics2D g=image.createGraphics();
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));
		g.setColor(color);
		g.fillRect(0, 0, width, height);
		g.setColor(reverse);
		System.out.println("text:"+text);
		g.drawString(text, 15, 15);
		for(int i=0,n=rdm.nextInt(20);i<n;i++){
			g.drawRect(rdm.nextInt(width),rdm.nextInt(height),1,1);
		}
       g.dispose();
       return image;
    }
    private void generatorImageBytes(BufferedImage image){
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       try{
           javax.imageio.ImageIO.write(image, "jpg", bos);
           this.bytes = bos.toByteArray();
       }catch(Exception ex){
       }finally{
           try{
              bos.close();
           }catch(Exception ex1){
           }
       }
    }
    
    public String doDefault(){   
       this.generateText();
       BufferedImage image = this.createImage();
       this.generatorImageBytes(image);
       System.out.println("_"+ServletActionContext.getRequest().getSession().getAttribute(SessionName));
       return "image";
    }
}

package yzm;
import com.opensymphony.xwork2.ActionSupport;

import java.util.Random;

import java.awt.*;

import java.awt.image.*;

import java.io.ByteArrayOutputStream;

 

import org.apache.struts2.ServletActionContext;

 

public class Images extends ActionSupport {
	//成生四位数字的图片
    /**
     * 锟斤拷证锟斤拷锟接︼拷锟絊ession锟斤拷
     */
    private static final String SessionName = "CheckCodeImageAction";
    private static final Random rdm = new Random();
    /**
     * 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷证锟斤拷锟斤拷锟斤拷源
     */
    private static final char[] source = new char[]{
    	'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M'
		,'N','P','Q','R','S','T','U','V','W','X','Y','Z'
    };
    /**
     * 锟斤拷锟斤拷锟斤拷锟斤拷印锟斤拷证锟斤拷锟斤拷址锟斤拷锟缴?
     */
    public static Color getRandomColor(){
		return new Color(rdm.nextInt(255),rdm.nextInt(255),rdm.nextInt(255));
	}
	
	public static Color getReverseColor(Color c){
		return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
	}
    /**
     * 锟斤拷锟节达拷印锟斤拷证锟斤拷锟斤拷锟斤拷锟?
     */
    private static final Font font = new Font(Font.SANS_SERIF,Font.BOLD, 16);
    /**
     * 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟?
     */
    private String text = "";
    private byte[] bytes = null;
    private String contentType = "image/jpeg";
    public byte[] getImageBytes(){
       return this.bytes;
    }
    public String getContentType(){
       return this.contentType;
    }
    public void setContentType(String value){
       this.contentType = value;
    }
    public int getContentLength(){
       return bytes.length;
    }
    /**
     * 锟斤拷沙锟斤拷锟轿?锟斤拷锟斤拷锟斤拷址锟?
     * @return 
     */
    private void generateText(){
       char[] source = new char[4];
       for(int i=0; i<source.length; i++){
           source[i] = Images.source[rdm.nextInt(Images.source.length)];
       }
       this.text = new String(source);
       // 锟斤拷锟斤拷Session
       ServletActionContext.getRequest().getSession().setAttribute(SessionName,this.text);
    }
    /**
     * 锟斤拷锟节达拷锟斤拷锟斤拷纱锟接★拷锟斤拷锟斤拷锟街凤拷锟酵计?
     * @return 锟斤拷锟节达拷锟叫达拷锟斤拷锟侥达拷印锟斤拷锟街凤拷锟酵计?
     */
    private BufferedImage createImage(){
       int width = 70;
       int height = 20;
       Color color=Color.BLACK;
		Color reverse=getReverseColor(color);
       BufferedImage image =
           new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		Graphics2D g=image.createGraphics();
		g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));
		g.setColor(color);
		g.fillRect(0, 0, width, height);
		g.setColor(reverse);
		g.drawString(text, 15, 15);
		for(int i=0,n=rdm.nextInt(20);i<n;i++){
			g.drawRect(rdm.nextInt(width),rdm.nextInt(height),1,1);
		}
       g.dispose();
       return image;
    }
    /**
     * 锟斤拷锟酵计拷锟斤拷锟斤拷纸锟斤拷锟斤拷锟?
     * @param image 锟斤拷锟节达拷锟斤拷锟街斤拷锟斤拷锟斤拷锟酵计?
     */
    private void generatorImageBytes(BufferedImage image){
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       try{
           javax.imageio.ImageIO.write(image, "jpg", bos);
           this.bytes = bos.toByteArray();
       }catch(Exception ex){
       }finally{
           try{
              bos.close();
           }catch(Exception ex1){
           }
       }
    }
    /**
     * 锟斤拷struts2锟斤拷锟斤拷锟斤拷锟斤拷锟矫的凤拷锟斤拷
     * @return 锟斤拷远锟斤拷锟斤拷锟街凤拷"image"
     */
    public String doDefault(){   
       this.generateText();
       BufferedImage image = this.createImage();
       this.generatorImageBytes(image);
       System.out.println("_"+ServletActionContext.getRequest().getSession().getAttribute(SessionName));
       return "image";
    }
}




两种验证码