如何在jsp页面中显示验证码:
- 验证码:<img class="yzm_img" align="middle" id="validateImage" src="imageCode.action" width="150" height="40" onclick=""http://blog.51cto.com/viewpic.php?refimg=" + this.src='imageCode.action?time-'+(new Date()).getTime();"/>
自动发送imageCode.action请求,struts2配置文件如下所写:
- <!-- 验证码图片 -->
- <action name="imageCode" class="org.tarena.action.user.ImageAction">
- <result name="success" type="stream">
- <param name="inputName">imageStream</param>
- <param name="bufferSize">2048</param>
- </result>
- </action>
相应的action如下:
- public class ImageAction {
- private InputStream imageStream;
- public InputStream getImageStream() {
- return imageStream;
- }
- public void setImageStream(InputStream imageStream) {
- this.imageStream = imageStream;
- }
- public String execute(){
- Map<String,BufferedImage> map = ImageUtil.getImage();
- //获取验证图片上的字符,保存到session
- String key = map.keySet().iterator().next();
- Map<String,Object> session = ActionContext.getContext().getSession();
- session.put("code", key);
- //获取验证图片,以stream方式响应
- BufferedImage image = map.get(key);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
- try {
- jpeg.encode(image);
- byte[] bts = bos.toByteArray();
- imageStream = new ByteArrayInputStream(bts);
- return "success";
- } catch (IOException e) {
- e.printStackTrace();
- return "error";
- }
- }
- }
其中ImageUtil类如下:
- public final class ImageUtil {
- private static final String[] chars = { "2", "3", "4", "5", "6",
- "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h" };
- private static final int SIZE = 5;
- private static final int LINES = 20;
- private static final int WIDTH = 200;
- private static final int HEIGHT = 100;
- private static final int FONT_SIZE = 60;
- public static Map<String,BufferedImage> getImage() {
- StringBuffer sb = new StringBuffer();
- BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
- BufferedImage.TYPE_INT_RGB);
- Graphics graphic = image.getGraphics();
- graphic.setColor(Color.LIGHT_GRAY);
- graphic.fillRect(0, 0, WIDTH, HEIGHT);
- Random ran = new Random();
- //������ַ�
- for(int i=1;i<=SIZE;i++){
- int r = ran.nextInt(chars.length);
- graphic.setColor(getRandomColor());
- graphic.setFont(new Font(null,Font.BOLD+Font.ITALIC,FONT_SIZE));
- graphic.drawString(chars[r],(i-1)*WIDTH/SIZE , HEIGHT/2);
- sb.append(chars[r]);//���ַ�������Session
- }
- //��������
- for(int i=1;i<=LINES;i++){
- graphic.setColor(getRandomColor());
- graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH),ran.nextInt(HEIGHT));
- }
- Map<String,BufferedImage> map = new HashMap<String,BufferedImage>();
- map.put(sb.toString(), image);
- return map;
- }
- private static Color getRandomColor(){
- Random ran = new Random();
- Color color = new Color(ran.nextInt(256),ran.nextInt(256),ran.nextInt(256));
- return color;
- }
- }
这样action就返回一个流文件到img标签所在的位置,并直接显示出来。
如果想增加“看不清楚换一张的功能”,那就重新再走一遍action,每走一次生成的验证码图片都是随机的。
如何验证填写的验证码是正确的呢?如下:
在页面中使用jquery
- $(function(){
- //验证码校验
- $("#validateCode").blur(function(){
- flag.validateCode=false;
- var txt = $(this).val();
- if(txt==""){
- $("#msg").html("<img src='../images/right.gif'/>不能为空!");//生成警告图片
- }else{
- $.post(
- "valid.action?dt="+new Date().getTime(),
- {"code":txt},
- function(data){
- if(data.ok){
- $("#numberInfo").html("<img src='../images/right.gif'/>验证码正确!");
- flag.validateCode=true;
- }else{
- $("#numberInfo").html("<img src='../images/wrong.gif'/>验证码不正确!");
- }
- },
- "json"
- );
- }
- });
- });
使用了ajax局部刷新,里面的#msg,#numberInfo这都是一些div块的id,这就不用多说了,下面再写一下valid.action所指向的action:
struts2配置文件中如下所写:
- <!-- Ajax请求校验验证码 -->
- <action name="valid" class="org.tarena.action.user.ValidImageAction">
- <result name="success" type="json"></result>
- </action>
则所指向的action为ValidImageAction:
- public class ValidImageAction {
- private String code = "";
- private boolean ok = false;
- public boolean isOk() {
- return ok;
- }
- public void setOk(boolean ok) {
- this.ok = ok;
- }
- public String execute(){
- Map<String,Object> session = ActionContext.getContext().getSession();
- //HttpServletRequest request=ServletActionContext.getRequest();
- String scode = (String)session.get("code");
- if(code.equals(scode)){
- ok = true;
- }else{
- ok = false;
- }
- return "success";
- }
- @JSON(serialize=false)//防止code值参与json串行化返回
- public String getCode() {
- return code;
- }
- public void setCode(String code) {
- this.code = code;
- }
- }
以上使用的是struts2做控制器,如果是servlet或者struts也一样,稍微改动一下