欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA验证码工具实例代码

程序员文章站 2022-06-30 23:45:44
工具类: package com.lhy.web.servlet; import java.awt.basicstroke; import java.awt....

工具类:

package com.lhy.web.servlet;
import java.awt.basicstroke;
import java.awt.color;
import java.awt.font;
import java.awt.graphics2d;
import java.awt.image.bufferedimage;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.outputstream;
import java.util.random;
import javax.imageio.imageio;
public class verifycode {
  private int w = 70;//图片长
  private int h = 35;//图片宽
   private random r = new random();//random类 生成随机数
   // 列举验证图片中验证码的字体类型
   //{"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_gb2312"}
  private string[] fontnames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_gb2312"};
  // 验证码可选字符
  private string codes="23456789abcdefghjkmnopqrstuvwxyzabcdefghjkmnpqrstuvwxyz";
  // 背景色
  private color bgcolor = new color(255, 255, 255);
  // 验证码上的文本
  private string text ;
  // 生成随机的颜色
  private color randomcolor () {
      int red = r.nextint(150);
      int green = r.nextint(150);
      int blue = r.nextint(150);
      return new color(red, green, blue);
  }
  // 生成随机的字体
  private font randomfont () {
        int index = r.nextint(fontnames.length);
        string fontname = fontnames[index];//生成随机的字体名称
        int style = r.nextint(4);//生成随机的样式, 0(无样式), 1(粗体), 2(斜体), 3(粗体+斜体)
        int size = r.nextint(5) + 24; //生成随机字号, 24 ~ 28
        return new font(fontname, style, size);
  }
  // 画干扰线
  private void drawline (bufferedimage image) {
      int num = 3;//一共画3条
      graphics2d g2 = (graphics2d)image.getgraphics();
      for(int i = 0; i < num; i++) {//生成两个点的坐标,即4个值
        int x1 = r.nextint(w);
        int y1 = r.nextint(h);
        int x2 = r.nextint(w);
        int y2 = r.nextint(h); 
        g2.setstroke(new basicstroke(1.5f)); 
        g2.setcolor(color.blue); //干扰线是蓝色
        g2.drawline(x1, y1, x2, y2);//画线
      }
  }
  // 随机生成一个字符
  private char randomchar () {
      int index = r.nextint(codes.length());
      return codes.charat(index);
  }
  // 创建bufferedimage
  private bufferedimage createimage () {
      //宽,高,图片的类型
      bufferedimage image = new bufferedimage(w, h, bufferedimage.type_int_rgb); 
      graphics2d g2 = (graphics2d)image.getgraphics(); 
      g2.setcolor(this.bgcolor);
      g2.fillrect(0, 0, w, h);
       return image;
  }
  // 返回验证码图片上的文本
  public string gettext () {
      return text;
  }
  // 保存图片到指定的输出流
  public static void output (bufferedimage image, outputstream out) 
          throws ioexception {
      imageio.write(image, "jpeg", out);
  }
  // 调用这个方法得到验证码
    public bufferedimage getimage () {
        bufferedimage image = createimage();//创建图片缓冲区 
        graphics2d g2 = (graphics2d)image.getgraphics();//得到绘制环境
        stringbuilder sb = new stringbuilder();//用来装载生成的验证码文本
        // 向图片中画4个字符
        for(int i = 0; i < 4; i++) {//循环四次,每次生成一个字符
          string s = randomchar() + "";//随机生成一个字母 
          sb.append(s); //把字母添加到sb中
          float x = i * 1.0f * w / 4; //设置当前字符的x轴坐标
          g2.setfont(randomfont()); //设置随机字体
          g2.setcolor(randomcolor()); //设置随机颜色
          g2.drawstring(s, x, h-5); //画图
        }
        this.text = sb.tostring(); //把生成的字符串赋给了this.text
        drawline(image); //添加干扰线
        return image;    
    }
    public static void main(string[] args) throws filenotfoundexception, ioexception {
      verifycode vc = new verifycode();//创建verifycode类的对象
      bufferedimage bi = vc.getimage();//调用getimge()方法获得一个bufferedimage对象
      verifycode.output(bi, new fileoutputstream("c:/验证码3.jpg"));//调用静态方法output()方法将图片保存在文件输出流中
      system.out.println(vc.gettext());//在控制台上打印验证码的文本值
    }
}

verifycodeservlet:

package com.lhy.web.servlet;
import java.awt.image.bufferedimage;
import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
public class verifycodeservlet extends httpservlet {
  public void doget(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    /*
     * 1. 生成图片
     * 2. 保存图片上的文本到session域中
     * 3. 把图片响应给客户端
     */
    verifycode vc = new verifycode();
    bufferedimage image = vc.getimage();
    request.getsession().setattribute("session_vcode", vc.gettext());//保存图片上的文本到session域
    verifycode.output(image, response.getoutputstream());
  }
}

loginservlet:

package com.lhy.web.servlet;
import java.io.ioexception;
import javax.servlet.requestdispatcher;
import javax.servlet.servletexception;
import javax.servlet.http.cookie;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
public class loginservlet extends httpservlet {
  public void dopost(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    /*
     * 校验验证码
     * 1. 从session中获取正确的验证码
     * 2. 从表单中获取用户填写的验证码
     * 3. 进行比较!
     * 4. 如果相同,向下运行,否则保存错误信息到request域,转发到login.jsp
     */
    string sessioncode = (string) request.getsession().getattribute("session_vcode");
    string paramcode = request.getparameter("verifycode");
    if(!paramcode.equalsignorecase(sessioncode)) {
      request.setattribute("msg", "验证码错误!");
      request.getrequestdispatcher("/login.jsp").forward(request, response);
      return;
    }
    /*
     * 1. 获取表单数据
     */
    // 处理中文问题
    request.setcharacterencoding("utf-8");
    // 获取
    string username = request.getparameter("username");
    string password = request.getparameter("password");
    /*
     * 2. 校验用户名和密码是否正确
     */
    if("itcast".equalsignorecase(username)) {//登录成功
      /*
       * 附加项:把用户名保存到cookie中,发送给客户端浏览器
       * 当再次打开login.jsp时,login.jsp中会读取request中的cookie,把它显示到用户名文本框中
       */
      cookie cookie = new cookie("uname", username);//创建cookie
      cookie.setmaxage(60*60*24);//设置cookie命长为1天
      response.addcookie(cookie);//保存cookie
      /*
       * 3. 如果成功
       *  > 保存用户信息到session中
       *  > 重定向到succ1.jsp
       */
      httpsession session = request.getsession();//获取session
      session.setattribute("username", username);//向session域中保存用户名
      response.sendredirect("/test/succ1.jsp");
    } else {//登录失败
      /*
       * 4. 如果失败
       *  > 保存错误信息到request域中
       *  > 转发到login.jsp
       */
      request.setattribute("msg", "用户名或密码错误!");
      requestdispatcher qr = request.getrequestdispatcher("/login.jsp");//得到转发器
      qr.forward(request, response);//转发
    }
  }
  }

login.jsp:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%string path = request.getcontextpath();
string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path+"/";
%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
 <head>
  <base href="<%=basepath%>" rel="external nofollow" >
  <title>my jsp 'login.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">
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
  -->
<script type="text/javascript">
function _change() {
  /*
  1. 得到img元素
  2. 修改其src
  */
  var imgele = document.getelementbyid("img");
  imgele.src = "<%=basepath%>servlet/verifycodeservlet?a=" + new date().gettime();
}
</script>
 </head>
 <body>
<%-- 本页面提供登录表单,还要显示错误信息 --%>
<h1>登录</h1>
<%
/*
读取名为uname的cookie!
如果为空显示:""
如果不为空显示:cookie的值
*/
string uname = "";
cookie[] cs = request.getcookies();//获取请求中所有的cookie
if(cs != null) {// 如果存在cookie
  for(cookie c : cs) {//循环遍历所有的cookie
    if("uname".equals(c.getname())) {//查找名为uname的cookie
      uname = c.getvalue();//获取这个cookie的值,给uname这个变量
    }
  }
}
%>
<%
  string message = "";
  string msg = (string)request.getattribute("msg");//获取request域中的名为msg的属性
  if(msg != null) {
    message = msg;
  }
%>
<font color="red"><b><%=message %> </b></font>
<form action="servlet/loginservlet" method="post">
      <%-- 把cookie中的用户名显示到用户名文本框中 --%>
  用户名:<input type="text" name="username" value="<%=uname%>"/><br/>
  密 码:<input type="password" name="password"/><br/>
  验证码:<input type="text" name="verifycode" size="3"/>
      <img id="img" src="<%=basepath%>servlet/verifycodeservlet"/>
      <a href="javascript:_change()" rel="external nofollow" >换一张</a>
      <br/>
  <input type="submit" value="登录"/>
</form>
 </body>
</html>

loginsuccess:

<body>
<h1>succ1</h1>
<%
string username = (string)session.getattribute("username");
if(username == null) {
  /*
  1. 向request域中保存错误信息,转发到login.jsp
  */
  request.setattribute("msg", "您还没有登录!请先登录!");
  request.getrequestdispatcher("/login.jsp").forward(request, response);
  return;
}
%>

欢迎欢迎,热烈欢迎,欢迎<%=username %>领导指导工作!

 </body>
</html>

配置文件:

<servlet>
  <servlet-name>loginservlet</servlet-name>
  <servlet-class>com.lhy.web.servlet.loginservlet</servlet-class>
 </servlet>
  <servlet-mapping>
  <servlet-name>loginservlet</servlet-name>
  <url-pattern>/servlet/loginservlet</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>verifycodeservlet</servlet-name>
  <servlet-class>com.lhy.web.servlet.verifycodeservlet</servlet-class>
 </servlet>
  <servlet-mapping>
  <servlet-name>verifycodeservlet</servlet-name>
  <url-pattern>/servlet/verifycodeservlet</url-pattern>
 </servlet-mapping>

建议:生成验证码的servlet最好设置成不缓存,这样就不用再页面请求验证码图片的时候加上时间戳了,加上时间戳就是欺骗浏览器防止浏览器读取缓存里的验证码图片,而点击换一张后没反应。 这样的不是很好的一点就是,每次点击换一张,浏览器都会把新获取的图片缓存到本地,而在servlet里设置不缓存,就不会缓存到本地了。

总结

以上所述是小编给大家介绍的java验证码工具实例代码,希望对大家有所帮助