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

Struts2生成验证码

2015-12-11 21:10 531 查看
在做登录或者注册的时候都会用到验证码,当然了,如今12306的验证码可谓是坑到姥姥家了。那么高大上的还是算了,今天就来搞一个简单的验证码。
首先,普通验证码的原理是,在后台生成一张数字和字母组成的图片,将字符串保存到session中,当用户输入后比较两个字符串的内容是否相同。如果你曾经做过servlet的验证码,那么久更加简单了。其实原理是一样的。好的,废话不多说开始上代码。
首先我们可以单独做一个工具类,用户生成这张图片。当然了,要生成图片,我们肯定会用到BufferedImage。至于验证码的内容你想搞复杂点,或者花样多点自己去做处理就是了,我这里就只是用数字、字母大小写组成。另外加了点灰点做干扰。下面是工具类


public class MyUtils {
public static BufferedImage getCodeImage(HttpSession session)
{
char[] resource = new char[]{'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','L','M','N','O','P','Q','R','S','U','V','W','X','Y','Z'};

Color[] color = new Color[]{Color.BLACK,Color.BLUE,Color.CYAN,Color.DARK_GRAY,Color.GRAY
,Color.GREEN,Color.LIGHT_GRAY,Color.YELLOW,Color.RED,Color.ORANGE,Color.PINK};

String codeString = "";
char[] code = new char[4];
Random random = new Random();
for(int i=0;i<4;i++)
{
char c = resource[random.nextInt(resource.length)];
code[i] = c;
codeString += c;
}

BufferedImage bimage = new BufferedImage(90, 30,
BufferedImage.TYPE_INT_RGB);
Graphics g = bimage.getGraphics();

g.setColor(Color.WHITE);
g.fillRect(0, 0, 90, 30);

int index = 0;

g.setFont(new Font("微软雅黑", Font.BOLD, 24));
for(int i=0;i<codeString.length();i++)
{
g.setColor(color[random.nextInt(color.length)]);

g.drawString(code[i]+"", i*20, 20);
}

g.setColor(Color.LIGHT_GRAY);
for(int i = 0;i < code.length * 6;i++){
int x = random.nextInt(90);
int y = random.nextInt(20);
g.drawRect(x, y, 1, 1);
}

session.setAttribute("codeValue", codeString);//将信息写到session
g.dispose();

return bimage;

}

}


代码没什么看不懂的,所以就没写注释了。

Ok,有了能生成验证码图片的工具类了,接下来我们就可以写action了。

public class LoginAction extends ActionSupport{

public String getCodeImage() throws Exception{
HttpSession session = request.getSession();//获取session
HttpServletResponse response = ServletActionContext.getResponse();//获取response

BufferedImage bimage = MyUtils.getCodeImage(session);//调用工具类获取验证图片
ServletOutputStream out = response.getOutputStream();//获取输出流
ImageIO.write(bimage, "jpeg", out);//将图片写到输出流
out.flush();//刷新流
out.close();//关闭流

return null;//返回null就行
}
}


由于这次请求只是从后台获取验证图片,所以并不需要任何结果集。所以struts.xml相当简单,只需要声明这个action就ok了。(其它博客可能会用到返回stream什么,其实没必要,就直接通过流写回页面就可以了)
下面就是struts.xml配置文件


<action name="CodeImage" class="com.pzhu.studentmanage.action.LoginAction" method="getCodeImage">
</action>


是的,你没有看错就是这么简单。
好的,最后再看看页面吧。用的最原始的标签。其它的也没贴上来,没啥意义,看这个就好。图片上加了一个点击事件。


<tr><td>验证码:</td><td><input type="text" name="code" id="code" onblur="verifycode()"/></td><td><img id="codeok" /></td><td><img src="Login!getCodeImage.action" onclick="this.src='Login!getCodeImage.action?'+Math.random()" title="点击图片刷新"/></td></tr>


好了,这就是我用Struts2做的验证码。欢迎交流!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: