/*=============================================================================
*
* 変更履歴 :2007/03/13 戴广久 新規作成
*
* Copyright(c)2007 ASCII SOLUTIONS,Inc.all rights reserved
============================================================================*/
package ebice.common.util;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 画像認証生成クラス
*
* @version 0.1, 2007/03/23
* @author ASCII 戴广久
*/
public class RandImage extends HttpServlet {
/** serialVersionUID */
private static final long serialVersionUID = -2488837459603294129L;
/**
* コンストラクター
*/
public RandImage()
{
super();
}
/**
* 画像認証生成する
*
* @param request リクエスト
* @param response レスポンス
* @throws IOException 例外
* @throws ServletException 例外
*/
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException,
ServletException {
response.reset();
response.setContentType( "image/png" );
response.setHeader( "Pragma", "No-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
try {
String randKey = RandomGraphic.createInstance( 8 ).drawAlpha( RandomGraphic.GRAPHIC_JPEG,
response.getOutputStream() );
request.getSession().setAttribute( "RandKey", randKey );
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
/*=============================================================================
*
* 変更履歴 :2007/03/24 戴广久 新規作成
*
* Copyright(c)2007 ASCII SOLUTIONS,Inc.all rights reserved
============================================================================*/
package ebice.common.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 認証画像の生成クラス
*
* @version 0.1, 2007/03/24
* @author ASI 戴广久
*/
public class RandomGraphic {
/** WORD_HEIGHT */
private static final int GRAPH_HEIGHT = 234;
/** WORD_WIDTH */
private static final int GRAPH_WIDTH = 60;
/** WORD_HEIGHT */
private static final int WORD_HEIGHT = 16;
/** WORD_WIDTH */
private static final int WORD_WIDTH = 25;
/** FONT_SIZE */
private static final int FONT_SIZE = 35;
/** MAX_CHARCOUNT */
private static final int MAX_CHARCOUNT = 16;
/** initypos */
private final int initypos = 10;
/** initypos */
private final int intNext = 12;
/** 文字数 */
private int charCount = 8;
/** BACK_COLOR */
private static final int BACK_COLOR = 0xFFFFCC;
/** 文字色 */
private static final int[] CHAR_COLOR = {0x000099, 0xFF6699, 0x666600, 0xCC0066, 0x009933 };
/** 線色 */
private static final int[] LINE_COLOR = {0xFF6633, 0x9966FF, 0x66FF33, 0x6699FF, 0x006633 };
/** r */
private Random r = new Random();
/** GRAPHIC_JPEG */
public static final String GRAPHIC_JPEG = "JPEG";
/** GRAPHIC_PNG */
public static final String GRAPHIC_PNG = "PNG";
/**
* コンストラクター
*
* @param charCount 文字数
*/
protected RandomGraphic( int charCount )
{
this.charCount = charCount;
}
/**
* メソッドの概要
*
* @param charCount 文字数
* @return RandomGraphic
* @exception Exception 例外
*/
public static RandomGraphic createInstance( int charCount ) throws Exception {
if ( charCount < 1 || charCount > MAX_CHARCOUNT ) {
throw new Exception( "Invalid parameter charCount,charCount should between in 1 and 16" );
}
return new RandomGraphic( charCount );
}
/**
* メソッドの概要
*
* @param graphicFormat グラフのタイプ
* @param out OutputStream
* @return String
* @exception IOException 例外
*/
public String drawAlpha( String graphicFormat, OutputStream out ) throws IOException {
String charValue = "";
charValue = getRandKeys( charCount );
return draw( charValue, graphicFormat, out );
}
/**
* メソッドの概要
*
* @param charValue 文字
* @param graphicFormat グラフのタイプ
* @param out OutputStream
* @return String
* @exception IOException 例外
*/
private String draw( String charValue, String graphicFormat, OutputStream out ) throws IOException {
int w = ( charCount + 2 ) * WORD_WIDTH;
int h = WORD_HEIGHT * 3;
BufferedImage bi = new BufferedImage( w, h, BufferedImage.TYPE_3BYTE_BGR );
Graphics2D g = bi.createGraphics();
Color backColor = new Color( BACK_COLOR );
g.setBackground( backColor );
g.fillRect( 0, 0, w, h );
g.setFont( new Font( "Century", Font.BOLD, FONT_SIZE ) );
for ( int i = 0; i < charCount; i++ ) {
String c = charValue.substring( i, i + 1 );
Color color = new Color( CHAR_COLOR[ randomInt( 0, CHAR_COLOR.length ) ] );
g.setColor( color );
int xpos = ( i + 1 ) * WORD_WIDTH - 5;
int ypos = randomInt( initypos + WORD_HEIGHT, initypos + WORD_HEIGHT * 2 );
g.drawString( c, xpos, ypos );
}
Random random = new Random();
for ( int i = 0; i < 100; i++ ) {
Color color = new Color( LINE_COLOR[ randomInt( 0, LINE_COLOR.length ) ] );
g.setColor( color );
int x = random.nextInt( GRAPH_HEIGHT );
int y = random.nextInt( GRAPH_WIDTH );
int xl = random.nextInt( intNext );
int yl = random.nextInt( intNext );
g.drawLine( x, y, x + xl, y + yl );
g.drawLine( x, y + 1, x + xl, y + yl + 1 );
// g.drawLine( x, y +2, x + xl, y + yl + 2 );
// g.drawLine( x, y +3, x + xl, y + yl + 3 );
// g.drawLine( x, y +4, x + xl, y + yl + 4 );
}
g.dispose();
bi.flush();
ImageIO.write( bi, graphicFormat, out );
return charValue;
}
/**
* メソッドの概要
*
* @param intLength 長さ
* @return String
*/
public static final String getRandKeys( int intLength ) {
String retStr = "";
String strTable = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";
int len = strTable.length();
boolean bDone = true;
do {
retStr = "";
int count = 0;
for ( int i = 0; i < intLength; i++ ) {
double dblR = Math.random() * len;
int intR = (int) Math.floor( dblR );
char c = strTable.charAt( intR );
if ( ( '0' <= c ) && ( c <= '9' ) ) {
count++;
}
retStr += strTable.charAt( intR );
}
if ( count >= 2 ) {
bDone = false;
}
} while ( bDone );
return retStr;
}
/**
* メソッドの概要
*
* @param from から
* @param to まで
* @return int
*/
private int randomInt( int from, int to ) {
return from + r.nextInt( to - from );
}
}
JSP:
画像認証 ※
再在WEB.xml中做以下配置:
RandImage
ebice.common.util.RandImage
RandImage
/RandImage
这样页面就可以显示随机生成的验证码了,JSP提交之后需要验证是否正确可以利用这样的语句!
// 从session中取得随即生成的验证码的值
String imageConfirm = (String) request.getSession().getAttribute( "RandKey" );
// 画像確認にチェック(和JSP中的文本框中的值比较)
if ( !imageConfirm.equals( showSiteUserInfoSiteForm.getImageConfirm() ) ) {
logger.error( Message.getMessage( "ErrCheck0025" ) );
errors.add( "imageconfirm", new ActionMessage( "ErrCheck0025" ) );
}
至此,这个简单的验证码功能就实现了!例子中都是本项目中的一些变量,如果使用只需稍加改动就OK!