获取验证码实例

来源:互联网 发布:ubuntu 回到根目录 编辑:程序博客网 时间:2024/05/21 06:16
 action类代码:

public class UserLoginAction extends ActionSupport
{
    /**
     * TODO 添加字段注释
     */
    private static final long serialVersionUID = 1L;
    /**
     * 调测日志记录器。
     */
    private static final DebugLog DEBUGGER = LogFactory
            .getDebugLog(UserLoginAction.class);
   
    /**
     * 客户输入的验证码
     */
    private String verifycode;
   
    /**
     * 图片输入流对象
     */
    private ByteArrayInputStream inputStream;
   
    @Override
    public String execute() throws Exception
    {
        DEBUGGER.info("UserLoginAction.execute()");
        if (!this.checkRandom()) {
            return "input";
        }
        return "userLoginSuccess";
    }

    /**
     * 产生随机数的方法
     *
     * @return String
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public String getRandom(){
        RandomNumUtil rdnu = RandomNumUtil.Instance();
        // 取得带有随机字符串的图片
        this.setInputStream(rdnu.getImage());

        // 取得随机字符串放入HttpSession
        ActionContext.getContext().getSession().put("random", rdnu.getStr());
        return SUCCESS;
    }

    /**
     * 验证随机数的方法
     *
     * @return String
     */
    public Boolean checkRandom() {
        // 取得session保存中的字符串
        String validateCode = (String) (ActionContext.getContext().getSession()
                .get("random"));

        String inputCode = this.getVerifycode();
        if (null == inputCode  || "".equals(inputCode))
        {
            return false;
        }
        if(null == validateCode || "".equals(validateCode))
        {
            return false;
        }

        // 下面就是将session中保存验证码字符串与客户输入的验证码字符串对比了
        if (inputCode.equals(validateCode))
        {
            return true;
        }
        else
        {
            HttpServletRequest request = ServletActionContext.getRequest();
            request.setAttribute("checkcodemessage",
                    "The Verification Code is wrong,Please input again!");
            return false;
        }

    }

    public ByteArrayInputStream getInputStream()
    {
        return inputStream;
    }

    public void setInputStream(ByteArrayInputStream inputStream)
    {
        this.inputStream = inputStream;
    }

    public String getVerifycode()
    {
        return verifycode;
    }

    public void setVerifycode(String verifycode)
    {
        this.verifycode = verifycode;
    }

}

获取随即数工具类:

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;

public class RandomNumUtil {
   
    //图像
    private ByteArrayInputStream image;
   
    //验证码
    private String str="";

    private RandomNumUtil(){
        //初始化属性
        init();
    }
    /**
     * 取得RandomNumUtil实例。
     *
     */
    public static RandomNumUtil Instance(){
        return new RandomNumUtil();
    }
    /**
     * 取得验证码图片。
     *
     */
    public ByteArrayInputStream getImage(){
        return this.image;
    }
    /**
     *
     * 取得图片的验证码。
     *
     */
    public String getStr()
    {
        return str;
    }
    public void setStr(String str)
    {
        this.str = str;
    }
   
    private void init() {
       
        //       在内存中创建图象
        int width=60, height=20;
        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);
        }
        //       取随机产生的认证码(6位数字)
        String sRand="";
        for (int i=0;i<4;i++){
            String rand=String.valueOf(random.nextInt(10));
            sRand+=rand;
            // 将认证码显示到图象中
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            //      调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成

            g.drawString(rand,13*i+6,16);
            this.str += rand;/*   赋值验证码   */
        }
        //       图象生效
        g.dispose();
        ByteArrayInputStream input=null;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try{
            ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
            ImageIO.write(image, "JPEG", imageOut);
            imageOut.close();
            input = new ByteArrayInputStream(output.toByteArray());
        }catch(Exception e){
            System.out.println("验证码图片产生出现错误:"+e.toString());
        }
       
        this.image=input;/*  赋值图像  */
    }
    /*
     * 给定范围获得随机颜色
     */
    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);
   }

}

 

jsp页面

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
 language="java" errorPage="./error.jsp" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>即信窗消息源管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<base href="<%=basePath%>" />
<link href="css/login.css" type="text/css" rel="Stylesheet" />
<link href="css/theme.css" type="text/css" rel="Stylesheet" />

<script type="text/javascript">
 function changeValidateCode(obj) {
  
     //获取当前的时间作为参数,无具体意义
   var timenow = new Date().getTime();
    
     //每次请求需要一个不同的参数,否则可能会返回同样的验证码
   //这和浏览器的缓存机制有关系,也可以把页面设置为不缓存,这样就不用这个参数了。
   obj.src="userLogin!getRandom.action?d="+timenow;
 
 }
 function loginsubmit()
 {
  alert('submit');
  document.form1.submit();
 }

</script>
</head>
<%
    //获取验证码错误提示信息
     String random = (String)session.getAttribute("random");
     String checkCode = (String)request.getAttribute("checkcodemessage");
    
 %>
<body onunload="checkBack();" class="login_bg">

<form name="form1" method="post" id="form1" action="userLogin.action">
<div id="login_body">
<table id="login_main_shadow" cellpadding="0" cellspacing="0">
 <tr>
  <td colspan="2" rowspan="2">
  <div id="login_main">
  <div class="logo"></div>
  <div class="main">
  <div class="center">
  <table cellpadding="0" cellspacing="0">
   <tr>
    <td class="title">用户名:
    </td>
    <td>
     <input type="text" id="userName" name="userName" tabindex="1" class="text" />
    </td>
   </tr>
   <tr>
    <td class="title">密码:
    </td>
    <td>
     <input id="password" name="password" type="password" tabindex="2" class="text" />
    </td>
   </tr>
   <tr>
    <td class="title">验证码:
    </td>
    <td>
     <!-- <input type="text" id="verifycode" name="rand" maxlength="4" tabindex="3" class="text" />
     <img id="verifycodeimg" src="verifycode.jsp" alt=""/> -->
     <input type="text" name="verifycode" id="verifycode" maxlength="4" tabindex="3" class="text"/>
     <img src="userLogin!getRandom.action" id="verifycodeimg"
     onclick="changeValidateCode(this)"/>
    </td>
   </tr>
   <tr>
    <td>&nbsp;</td>
    <td class="msgPanel"></td>
   </tr>
   <tr>
    <td></td>
    <td>
     <input type="button" value="登录" onclick="loginsubmit();" class="button" />
     &nbsp;&nbsp;
     <input type="reset" value="取消" class="button" />
    </td>
   </tr>
  </table>
  
  <table width="336" border="0" align="center" >
      <%
       if (null != checkCode && !"".equals(checkCode))            
       {
   %><tr>
    <td id="wrongcode">
     <script type="text/javascript">
      alert("<%=checkCode%>");       
     </script>
    </td>
   </tr>
  <%
     }
  %>
  </table>
  
  </div>
  </div>
  <div class="footer"></div>
  </div>
  </td>
  <td class="right_top"></td>
 </tr>
 <tr>
  <td class="right"></td>
 </tr>
 <tr>
  <td class="bottom_left"></td>
  <td class="bottom"></td>
  <td class="bottom_right"></td>
 </tr>
</table>
</div>
</form>
</body>
</html>

 action配置

<!-- 用户登录 -->
  <action name="userLogin" class="com.huawei.imw.omp.action.UserLoginAction">
   <result name="userLoginSuccess">
    /jsp/main.jsp
   </result>
   <result name="input">
    /jsp/login.jsp
   </result>
   <result type="stream">
    <param name="contentType">/image/jpeg</param>
    <param name="inputName">inputStream</param>
   </result>
  </action>

原创粉丝点击