struts 2 生成验证码

生成图片的action:  
package com.ray.lower.server.struts.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ImageAction extends ActionSupport {

/**
*/
private static final long serialVersionUID = 1L;

public void makeImage() throws Exception {
Map<String, Object> session = ActionContext.getContext().getSession();
HttpServletResponse res = ServletActionContext.getResponse();
BufferedImage img = new BufferedImage(68, 22,
BufferedImage.TYPE_INT_RGB);

// 得到该图片的绘图对象

Graphics g = img.getGraphics();

Random r = new Random();

Color c = new Color(200, 150, 255);

g.setColor(c);
// 填充整个图片的颜色
g.fillRect(0, 0, 68, 22);
// 向图片中输出数字和字母

StringBuffer sb = new StringBuffer();

char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

int index, len = ch.length;

for (int i = 0; i < 4; i++) {

index = r.nextInt(len);

g
.setColor(new Color(r.nextInt(88), r.nextInt(188), r
.nextInt(255)));

g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小

g.drawString("" + ch[index], (i * 15) + 3, 18);// 写什么数字,在图片的什么位置画

sb.append(ch[index]);

}
session.put("piccode", sb.toString());

ImageIO.write(img, "JPG", res.getOutputStream());

}

}

struts.xml中的配置:
<package name="member" extends="struts-default" namespace="/member">
<action name="image" class="com.ray.lower.server.struts.action.ImageAction" method="makeImage"></action>
</package>

jsp使用:
<img src="member/image!makeImage.action" id="piccode" align="top">//默认加载,记得加上namespace
    <a href="javascript:loadImg();">看不清</a>//调用js重新加载

<script type="text/javascript">
function loadImg() {
var piccode = document.getElementById('piccode');
alert(piccode);
piccode.src = 'member/image!makeImage.action?str='+new Date().toString();//需要加不能的参数,若不加,请求不到的
}
</script>
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页