Struts2 生成验证码

3 篇文章 0 订阅
ImageUtil.java
package com.ctl.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public final class ImageUtil {
	private static final char[] chars = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', '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', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
			'k', 'x', 'y', 'z', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
			'u', 'v', 'w' };
	private static final int SIZE = 4;
	private static final int LINES = 6;
	private static final int WIDTH = 100;
	private static final int HEIGHT = 60;
	private static final int FONT_SIZE = 30;

	public static Map<String, BufferedImage> createImage() {
		StringBuffer sb = new StringBuffer();
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		Random ran = new Random();
		Graphics graphic = image.getGraphics();
		graphic.setColor(new Color(55 + ran.nextInt(200),
				55 + ran.nextInt(200), 55 + ran.nextInt(200)));
		graphic.fillRect(0, 0, WIDTH, HEIGHT);
		// 画随机字符
		for (int i = 1; i <= SIZE; i++) {
			int r = ran.nextInt(chars.length);
			graphic.setColor(getRandomColor());
			graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
			graphic.drawString(chars[r] + "", (i - 1) * WIDTH / SIZE,
					HEIGHT / 2);
			sb.append(chars[r]);// 将字符保存,存入Session
		}
		// 画干扰线
		for (int i = 1; i <= LINES; i++) {
			graphic.setColor(getRandomColor());
			graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
					ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
		}
		Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
		map.put(sb.toString(), image);
		return map;
	}

	public static Color getRandomColor() {
		Random ran = new Random();
		Color color = new Color(ran.nextInt(256), ran.nextInt(256),
				ran.nextInt(256));
		return color;
	}

	public static InputStream getInputStream(BufferedImage image)
			throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
		encoder.encode(image);
		byte[] imageBts = bos.toByteArray();
		InputStream in = new ByteArrayInputStream(imageBts);
		return in;
	}
}






ImageAction.java
package com.ctl.util;

import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.Map; 

import javax.servlet.http.Cookie;

/** 
* 显示验证码的处理 
* @author tarena 
* 
*/ 
public class ImageAction extends BaseAction{ 
    //input 无 
    //output 
    //stream result只能输出inputStream类型的属性值 
    private InputStream imageStream; 
    public String execute() throws IOException{ 
        //生成一个验证码图片 
        Map<String,BufferedImage> map = 
            ImageUtil.createImage(); 
        String code = 
            map.keySet().iterator().next(); 
        BufferedImage image = map.get(code); 
        session.put("code", code);//用于验证 
        System.out.println(code);
        response.addCookie(new Cookie("code", code));
        //把图片给imageStream赋值 
        imageStream = 
            ImageUtil.getInputStream(image); 
        //调用stream result将imageStream输出 
        return "success"; 
    } 
    public InputStream getImageStream() { 
        return imageStream; 
    } 
    public void setImageStream(InputStream imageStream) { 
        this.imageStream = imageStream; 
    } 
}







struts.xml
<struts>
	<constant name="struts.multipart.maxSize" value="1048576000" /><!-- 
		限制上传的最大的字节数 -->

	<!-- 设置struts2 上传文件时 保存的临时目录 -->
	<constant name="struts.multipart.saveDir" value="C:\temp" /><!-- 
		临时目录 -->
	<package name="all" namespace="/" extends="struts-default">

		<!-- 产生验证码 -->
		<action name="image" class="com.ctl.util.ImageAction">
			<result type="stream">
				<param name="inputName">imageStream</param>
			</result>
		</action>
		<action name="upload" class="com.action.FileUploadAction">
			<result name="success">upload.jsp</result>
			<result name="input">upload.jsp</result>
		</action>
	</package>

</struts>    




html页面
<tr>

							<td class="login-text02">验证码:</td>
							<td class="width70"><input id="yzm" type="text" name="yzmn"
								size="10" class="width70" value="" /></td>

							<td><img src="<%=request.getContextPath()%>/image"
								style="width:45px;height:21px; margin-left: -130px"
								id="imageCode" alt="验证码" title="点击更换" /></td>

						</tr>
	// 变换验证码
	$('#imageCode').click(function() {
		$('#imageCode').attr('src', "image?ts="+Math.random());
	});
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{ 
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1 
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
		} 
	}
	return ""
}
function checkLogin() {


	var yzmv = document.frm.yzmn.value;
				if (yzmv == "") {
			alert("验证码不能为空");
			document.frm.yzmn.focus();
			return false;
		}
		var value=getCookie('code');
		//alert(value);
		if(yzmv!=value){
			alert("验证码错误");
			document.frm.yzmn.focus();
			return false;
		}
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值