这里我写了两种验证码,一种是随机生成四位数,还有一种是中文字的数学题加减题,其实就是生成图片上有点不同,别的地方一样。
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="<%=basePath%>">
<link href="<%=request.getContextPath() %>/css/init.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="<%=path%>/css/exam.css" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script>
function reloadImage(){
document.getElementById('identy').src='ValidateImage?ts='+new Date().getTime();
}
</script>
</head>
<body>
<img src="ValidateImage" id="identy" onClick="reloadImage()"/>
<form action="getzyms.action">
<input type="submit" value="在后台打印验证码1"/>
</form>
</body>
</html>
<?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="UTF-8"></constant>
<package name="yzm" extends="struts-default">
<result-types>
<result-type name="ValidateImage" class="yzm.ImageResult" />
</result-types>
<action name="ValidateImage" class="yzm.ImageAction" method="doDefault">
<result name="image" type="ValidateImage" />
</action>
<action name="getzyms" class="com.web.actoin.getyzm" method="getzyms">
</action>
</package>
</struts> 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";
}
}
原文地址:http://blog.csdn.net/u010935715/article/details/38857199