Java Web中验证码的实现

时间:2022-12-30 19:01:25

验证码本质上是一张图片,即应该用<img>标签,其中src属性决定了这是一张什么图片,因此可以让src为某一Action,每次点击时,都会更新这个src属性。

① 前台JSP页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/share/taglib.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'imgcode.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function changeValidateCode() {
var currentTime= new Date().getTime();
var obj=document.getElementById("js_randyzm");
obj.src = "imgCodeAction?time=" + currentTime;
}
</script>
</head>
<body>
验证码: <br>
<img src="<s:url action="imgCodeAction"></s:url>" onclick="changeValidateCode()" id="js_randyzm" height="25" width="70" />
<a href="javascript:changeValidateCode();" class="hyz">看不清楚,点击换一张</a>
</body>
</html>
当第一次跳转到该页面时,imgCodeAction就会被请求一次,以后只要点击图片或者超链接,就会更换一次验证码。注意:javascript代码中,如果没有time=xxxxxxxxx这个参数,则<img>标签的src属性就会一直是imgCodeAction 这个值,导致验证码不会更换,加这个参数是为了区分src属性。
②Action的实现

package edu.njcit.action.imgcode;

import edu.njcit.action.ActionSupportBase;
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.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ImgCodeAction extends ActionSupportBase {

private static final long serialVersionUID = 1L;
private ByteArrayInputStream inputStream;
@Override
public String execute() throws Exception {
final int width = 65; //验证码图片的宽
final int height = 20; //验证码图片的高
final int numCount = 4; //验证码个数(数字)
String randomString = ""; //随机产生的认证码字符串内容

// 在内存中创建图象
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}

for (int i = 0; i < numCount; i++) {
String rand = String.valueOf(random.nextInt(10));
randomString += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 6, 16);
}

// 将认证码存入SESSION,用于和用户输入的进行比较
ActionContext.getContext().getSession().put("randomString", randomString);
// 图象生效
g.dispose();
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
ImageIO.write(image, "JPEG", imageOut);
imageOut.close();
ByteArrayInputStream input = new ByteArrayInputStream(output
.toByteArray());
//设定字节流
this.setInputStream(input);
return ActionSupport.SUCCESS;
}
/*
* 给定范围获得随机颜色
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
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);
}

public void setInputStream(ByteArrayInputStream inputStream) {
this.inputStream = inputStream;
}
/**
* 对应struts.xml配置中<param name="inputName">inputStream</param>
* @return 字节流
*/
public ByteArrayInputStream getInputStream() {
return inputStream;
}
}

③struts2的配置文件中进行配置

<action name="imgCodeAction" class="edu.njcit.action.imgcode.ImgCodeAction">
<!-- 结果类型是字节流 -->
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action>

最终效果图如下:

Java Web中验证码的实现