您的位置:首页 > 编程语言 > Java开发

extjs ajax java简单精美验证码实现 有图

2016-06-07 20:28 357 查看
前端:利用ExtJs的autoEl功能加载图片。

var imgCheckValid = new Ext.create('Ext.Component',{
width: 70, //图片宽度
height: 45, //图片高度
margin:'5',
id:"imd_imgCheckValid",
autoEl: {
tag: 'img',    //指定为img标签
src: 'Code/genCodeImg.do?'    //指定url路径
},
listeners: {
render: function(component){
component.getEl().on('click', function(e){
this.dom.src = 'Code/genCodeImg.do?'+(new Date().getTime());  // autoEl不会自动加载,只有设置了不同的src才会加载
});
}
}
});


小编心得:autoEl会自动加载,要实现点击验证码刷新,登录失败刷新,方法是给请求的url加上时间戳。所以刷新验证码只要在需要刷新的时候重新设置加上时间戳的src即可。

疑问解答:为什么只是给了src一个路径,并没有给图片地址,页面能显示图片呢?

目前不是很清楚:猜想它是根据给的链接,自动从response中获得二进制资源。明确的是我会向response中写入流

后台:struts,spring配置

struts:

<!-- 客户端 -->
<package name="Code" extends="json" namespace="/Code">
<action name="genCodeImg" class="codeAction" method="genCodeImg">
<result name="success" type="json">
<param name="root">responseJson</param>
</result>
</action>
</package>


spring:

<!-- 验证码生成器--> <bean id="codeAction" class="com.sinsche.i.action.impl.CodeAction" scope="prototype"></bean>

后台:

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.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.common.core.st2.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import com.sinsche.i.action.ICodeAction;

public class CodeAction extends BaseAction implements  ICodeAction {
/**
*
*/
private static final long serialVersionUID = 6865491407475710154L;
private boolean success;
private String message;
// 图片的宽度。
private int width = 70;
// 图片的高度。
private int height = 45;
// 验证码字符个数
private int codeCount = 4;
// 验证码干扰线数
private int lineCount = 20;
// 验证码图片Buffer
private BufferedImage buffImg = null;
Random random = new Random();
public String genCodeImg() throws Exception {
HttpServletResponse resp = ServletActionContext.getResponse();
int fontWidth = width / codeCount;// 字体的宽度
int fontHeight = height - 5;// 字体的高度
int codeY = height - 8;

// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.getGraphics();
// Graphics2D g = buffImg.createGraphics();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);

// 设置字体
// Font font1 = getFont(fontHeight);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);

// 设置干扰线
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width);
int ye = ys + random.nextInt(height);
//            g.setColor(getRandColor(1, 255));
shear(g,1,20,getRandColor(1, 255));
g.drawLine(xs, ys, xe, ye);
}

// 添加噪点
float yawpRate = 0.01f;// 噪声率
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);

buffImg.setRGB(x, y, random.nextInt(255));
}

String str1 = randomStr(codeCount);// 得到随机字符
for (int i = 0; i < codeCount; i++) {
String strRand = str1.substring(i, i + 1);
g.setColor(getRandColor(1, 255));
// g.drawString(a,x,y);
// a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处

g.drawString(strRand, i * fontWidth + 3, codeY);
}

// 将四位数字的验证码保存到Session中。
Map<String, Object> map = ActionContext.getContext().getSession();
System.out.print(str1);
map.put("code", str1.toString());
// 禁止图像缓存。
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setDateHeader("Expires", 0);

resp.setContentType("image/jpeg");

// 将图像输出到Servlet输出流中。
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();

return null;
}

// 得到随机字符
private String randomStr(int n) {
String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
String str2 = "";
int len = str1.length() - 1;
double r;
for (int i = 0; i < n; i++) {
r = (Math.random()) * len;
str2 = str2 + str1.charAt((int) r);
}
return str2;
}

// 得到随机颜色
private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}

//    /**
//     * 产生随机字体
//     */
//    private Font getFont(int size) {
//        Font font[] = new Font[5];
//        font[0] = new Font("Ravie", Font.PLAIN, size);
//        font[1] = new Font("Antique Olive Compact", Font.PLAIN, size);
//        font[2] = new Font("Fixedsys", Font.PLAIN, size);
//        font[3] = new Font("Wide Latin", Font.PLAIN, size);
//        font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
//        return font[random.nextInt(5)];
//    }

// 扭曲方法
private void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}

private void shearX(Graphics g, int w1, int h1, Color color) {

int period = random.nextInt(2);

boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);

for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}

}

private void shearY(Graphics g, int w1, int h1, Color color) {

int period = random.nextInt(40) + 10; // 50;

boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}

}

}

public BufferedImage getBuffImg() {
return buffImg;
}
@Override
public String list() throws Exception {
return null;
}

@Override
public String create() throws Exception {
return null;
}

@Override
public String update() throws Exception {
return null;
}

@Override
public String delete() throws Exception {
return null;
}

@Override
public String listByPage() throws Exception {
return null;
}

public boolean isSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}


效果:











内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: