struts2与springmvc验证码

实现验证码的功能网上都比较的散,综合以前学的内容做一个总结,struts与springmvc都使用同一个ImagUtil.java,只是action不同。
当时学习的时候的一个ImageUtil.java如下
package com.zqw.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.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
* 验证码
* @author Administrator
*
*/
public 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'
};

private static final int SIZE = 4;
private static final int LINES = 5;
private static final int WIDTH = 80;
private static final int HEIGHT = 30;
private static final int FONT_SIZE = 28;

public static Map<String,BufferedImage> createIamge(){
BufferedImage image = new BufferedImage
(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, WIDTH, HEIGHT);
//随机获取4位字符
Random r = new Random();
StringBuilder sp = new StringBuilder();
for(int i=0;i<SIZE;i++){
int index = r.nextInt(chars.length);
g.setColor(getRandomColor());
g.setFont(new Font(null,Font.ITALIC,FONT_SIZE));
g.drawString(chars[index]+"", (i)*WIDTH/SIZE, HEIGHT/2+7);
sp.append(chars[index]);
}

// 画干扰线
for (int i = 1; i <= LINES; i++) {
g.setColor(getRandomColor());
g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT),
r.nextInt(WIDTH), r.nextInt(HEIGHT));
}


Map<String,BufferedImage> map =
new HashMap<String,BufferedImage>();
map.put(sp.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){
//压缩内存映像图片
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
//压缩图片
try {
encoder.encode(image);
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
InputStream input = new ByteArrayInputStream(bos.toByteArray());
return input;
}

}

[color=red]struts框架下:[/color]
生成验证码的CheckCodeActionStruts.java
package com.zqw.web.action;

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

import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.zqw.netctoss.util.ImageUtil;
@Controller
public class CheckCodeActionStruts {
private InputStream input;
public String execute(){

Map<String,BufferedImage> map = ImageUtil.createIamge();//产生图片
String code = map.keySet().iterator().next();
BufferedImage image = map.get(code);
ActionContext actionContext = ActionContext.getContext();
Map session = actionContext.getSession();
session.put("code", code);
input = ImageUtil.getInputStream(image);//压缩图片并输出
return "success";

}
public InputStream getInput() {
return input;
}
}

struts.xml的配置
		<action name="checkCode" class="com.zqw.web.action.CheckCodeActionStruts">
<result type="stream">
<param name="inputName">input</param>
</result>
</action>

springMVC框架下只是action稍有不同,[color=red]springMVC框架下:[/color]
package com.zqw.web.action;

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

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.zqw.netctoss.util.ImageUtil;
@Controller("checkCodeActionSpringMVC")
public class CheckCodeActionSpringMVC {
@RequestMapping(value="/checkCode.do" )
public void execute(HttpServletRequest req,HttpServletResponse resp) throws IOException{
Map<String,BufferedImage> map = ImageUtil.createIamge();//产生图片
String code = map.keySet().iterator().next();
BufferedImage image = map.get(code);
req.getSession().setAttribute("code", code);
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(image, "jpeg", sos);
sos.close();
}
}

都使用相同的前台页面,点击更换图片则是参考网上的写法。

function changeImg() {
var imgSrc = $("#imgObj");
var src = imgSrc.attr("src");
imgSrc.attr("src", chgUrl(src));
}
//时间戳
//为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳
function chgUrl(url) {
var timestamp = (new Date()).valueOf();
url = url.substring(0, 17);
if ((url.indexOf("&") >= 0)) {
url = url + "×tamp=" + timestamp;
} else {
url = url + "?timestamp=" + timestamp;
}
return url;
}
</script>


<td class="login_info">验证码:</td>
<td class="width70"><input name="checkCode" type="text" class="width70" /></td>
<td>[img]checkCode" alt="验证码" id="imgObj" onclick="changeImg()[/img]</td>
<td><span class="required"></span><br></td>
</tr>


如图:
[img]http://dl2.iteye.com/upload/attachment/0102/2786/36af2b3a-884d-3c9e-958a-67f3c11fdce9.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值