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

Java实现验证码具体代码

程序员文章站 2024-02-18 12:39:34
这里实现我使用到了struts2模拟一个登录功能来验证java实现的验证码功能。 java实现验证码的步骤: 1、创建randomimagegenerator.java...

这里实现我使用到了struts2模拟一个登录功能来验证java实现的验证码功能。

java实现验证码的步骤:

1、创建randomimagegenerator.java类,该类实现验证码图片的生成

2、创建一个servlet类,randomimageservlet.java,将生成的验证码输出到页面

3、创建一个action类,loginaction.java,控制登录

4、配置struts.xml一个web.xml文件

5、编写页面

具体实现用代码表达

1、创建randomimagegenerator.java类

复制代码 代码如下:

package com.tenghu.code;

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;

/**
 * 验证码生成类
 * @author xiaohu
 *
 */
public class randomimagegenerator {
 //创建random对象
 static random random=new random();
 //随机生成包含验证码字符串
 public static string random(int num){
  //初始化种子
  string[] str={"0","1","2","3","4","5","6","7","8","9",
       "a","b","c","d","e","f","g","h","i","j",
       "k","l","m","n","p","q","r","s","t"};
  int number=str.length;
  //接收随机字符
  string text = "";
  //随机产生4个字符的字符串
  for(int i=0;i<num;i++){
   text+=str[random.nextint(number)];
  }
  return text;
 }
 /**
  * 随机产生定义的颜色
  *
  * @return
  */
 private static color getrandcolor() {
  random random = new random();
  color color[] = new color[10];
  color[0] = new color(32, 158, 25);
  color[1] = new color(218, 42, 19);
  color[2] = new color(31, 75, 208);
  color[3] = new color(0, 102, 182);
  color[4] = new color(171, 0, 85);
  return color[random.nextint(5)];
 }
 /**
  * 产生随机字体
  *
  * @return
  */
 private static font getfont() {
  random random = new random();
  font font[] = new font[5];
  font[0] = new font("ravie", font.bold, 30);
  font[1] = new font("antique olive compact", font.bold, 30);
  font[2] = new font("forte", font.bold, 30);
  font[3] = new font("wide latin", font.bold, 30);
  font[4] = new font("gill sans ultra bold", font.bold, 30);
  return font[random.nextint(5)];
 }
 /**
  * 生成图片
  * @throws ioexception
  */
 public static void render(string randomstr,outputstream out,int width,int height) throws ioexception{
  //在内存中创建图像
  bufferedimage bi=new bufferedimage(width, height, bufferedimage.type_byte_indexed);
  //获取图形上下文
  graphics2d g=(graphics2d) bi.getgraphics();
  //话边框
  g.setcolor(color.white);
  g.fillrect(0, 0, width, height);
  g.setfont(getfont());
  g.setcolor(color.black);
  //画认证码,每个认证码在不同的水平位置
  string str1[]=new string[randomstr.length()];
  for(int i=0;i<str1.length;i++){
   str1[i]=randomstr.substring(i,i+1);
   int w=0;
   int x=(i+1)%3;
   //随机生成验证码字符水平偏移量
   if(x==random.nextint(7)){
    w=30-random.nextint(7);
   }else{
    w=30+random.nextint(7);
   }
   //随机生成颜色
   g.setcolor(getrandcolor());
   g.drawstring(str1[i], 20*i+10, w);
  }
  //随机产生干扰点,并用不同的颜色表示,事图像的认证码不易被其他程序探测到
  for(int i=0;i<100;i++){
   int x=random.nextint(width);
   int y=random.nextint(height);
   color color=new color(random.nextint(255), random.nextint(255), random.nextint(255));
   //随机画各种颜色的线
   g.setcolor(color);
   g.drawoval(x, y, 0, 0);
  }
  //画干扰线
  for(int i=0;i<15;i++){
   int x=random.nextint(width);
   int y=random.nextint(height);
   int x1=random.nextint(width);
   int y1=random.nextint(height);
   color color=new color(random.nextint(255), random.nextint(255), random.nextint(255));
   //随机画各种颜色线
   g.setcolor(color);
   g.drawline(x, y, x1, y1);
  }
  //图像生效
  g.dispose();
  //输出页面
  imageio.write(bi, "jpg", out);
 }
 public static void main(string[] args) throws filenotfoundexception, ioexception {
  //获取随机字符串
  string randomstr=random(5);
  system.out.println(randomstr);
  //生成图片
  render(randomstr, new fileoutputstream("d:\\test.jpg"),130,40);
 }
}

2、创建randomimageservlet.java

复制代码 代码如下:

package com.tenghu.code.servlet;

import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;

import com.tenghu.code.randomimagegenerator;

public class randomimageservlet extends httpservlet {
 //图片宽度
 int width=0;
 //图片高度
 int height=0;
 //图片上随机字符个数
 int randomstrnum=0;
 public void destroy() {
 }
 public void doget(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  dopost(request, response);
 }
 public void dopost(httpservletrequest request, httpservletresponse response)
   throws servletexception, ioexception {
  request.setcharacterencoding("utf-8");
  //获取httpsession对象
  httpsession session=request.getsession();
  //获取随机字符串
  string randomstr=randomimagegenerator.random(randomstrnum);
  if(null!=session){
   //设置参数
   session.setattribute("randomstr", randomstr);
   //设置响应类型,输出图片客户端不缓存
   response.setdateheader("expires", 1l); 
   response.setheader("cache-control", "no-cache, no-store, max-age=0");
   response.addheader("pragma", "no-cache");
   response.setcontenttype("image/jpeg"); 
   //输出到页面
   randomimagegenerator.render(randomstr, response.getoutputstream(), width, height);
  }
 }
 public void init() throws servletexception {
  //获取宽度
  width=integer.parseint(this.getinitparameter("width"));
  //获取高度
  height=integer.parseint(this.getinitparameter("height"));
  //获取个数
  randomstrnum=integer.parseint(this.getinitparameter("num"));
 }
}   

3、创建loginaction.java类

复制代码 代码如下:

package com.tenghu.code.action;

import java.io.bytearrayinputstream;
import java.io.inputstream;
import com.opensymphony.xwork2.actioncontext;
import com.opensymphony.xwork2.actionsupport;

public class loginaction extends actionsupport{
 //用户名
 private string username;
 //密码
 private string password;
 //验证码
 private string code;
 private inputstream inputstream;
 public inputstream getresult(){
  return inputstream;
 }
 //成功
 public string success() throws exception{
  return success;
 }
 //测试登录
 public string testlogin() throws exception{
  //获取图片的验证码
  string randomstr=(string) actioncontext.getcontext().getsession().get("randomstr");
  if(code.trim().equalsignorecase(randomstr)){
   if("admin".equals(username.trim())&&"admin".equals(password.trim())){
    //成功
    inputstream=new bytearrayinputstream("1".getbytes("utf-8"));
   }else{
    //用户名或密码错误
    inputstream=new bytearrayinputstream("2".getbytes("utf-8"));
   }
  }else{
   //验证码错误
   inputstream=new bytearrayinputstream("0".getbytes("utf-8"));
  }
  return "result";
 }
 public string getusername() {
  return username;
 }
 public void setusername(string username) {
  this.username = username;
 }
 public string getpassword() {
  return password;
 }
 public void setpassword(string password) {
  this.password = password;
 }
 public string getcode() {
  return code;
 }
 public void setcode(string code) {
  this.code = code;
 }
}

4、配置struts.xml、web.xml文件

复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<!doctype struts public
 "-//apache software foundation//dtd struts configuration 2.3//en"
 "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts> 
 <package name="installs" extends="struts-default">
  <action name="login" class="com.tenghu.code.action.loginaction">
   <!-- 登录成功到success.jsp页面 -->
   <result name="success">success.jsp</result>
   <!-- 登录验证返回的数据 -->
   <result name="result" type="stream">
    <param name="contenttype">text/html</param>
    <param name="inputname">result</param>
   </result>
  </action>
 </package>
</struts>

复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 xsi:schemalocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>this is the description of my j2ee component</description>
    <display-name>this is the display name of my j2ee component</display-name>
    <servlet-name>randomimageservlet</servlet-name>
    <servlet-class>com.tenghu.code.servlet.randomimageservlet</servlet-class>
    <!-- 初始化图片宽度 -->
    <init-param>
     <param-name>width</param-name>
     <param-value>130</param-value>
    </init-param>
    <!-- 初始化图片高度 -->
    <init-param>
     <param-name>height</param-name>
     <param-value>40</param-value>
    </init-param>
    <!-- 初始化图片随机数个数 -->
    <init-param>
     <param-name>num</param-name>
     <param-value>4</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>randomimageservlet</servlet-name>
    <url-pattern>/verification.do</url-pattern>
  </servlet-mapping>
  <!-- 配置struts核心过滤器 -->
  <filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>struts2</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

5、编写测试页面

复制代码 代码如下:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
  <head>
    <base href="<%=basepath%>">

    <title>my jsp 'index.jsp' starting page</title>
 <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
 <script type="text/javascript" src="js/jquery.form.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
   code.initcode();
   //验证输入
   function checkinput(){
    if($('#username').val()==''){
     alert('用户名不能为空!');
     return false;
    }
    if($('#password').val()==''){
     alert('密码不能为空!');
     return false;
    }
    if($('#code').val()==''){
     alert('验证码不能为空!');
     return false;
    }
    return true;
   }

   //点击按钮
   $('#btn').click(function(){
    if(checkinput()==true){
     $('#login_request').ajaxsubmit({
      url:'login!testlogin',
      cache:false,
      type:'post',
      success:function(data){
       if(data==0){
        alert('验证码错误!');
        //改变验证码
        code.initcode();
       }else if(data==1){
        alert('登录成功!');
        //提交到登录成功页面
        $('#login_request')[0].submit();
       }else if(data==2){
        alert('用户名或密码错误!');
        //改变验证码
        code.initcode();
       }
      },
      error:function(e){
       alert('出错了!');
      }
     });
     }
   });
  });
  var code={
    //初始化化验证码
    initcode:function(){
     $("#code_img").attr("src","verification.do?rmd="+new date().gettime())//如果需要点击图片改变图片的内容,则必须添加时间搓
     .click(function(){
      $(this).attr("src","verification.do?rmd="+new date().gettime());
     }); 
    }};
 </script>
  </head>

  <body>
   <form action="login!success" id="login_request" method="post">
    username:<input type="text" id="username" name="username"/><br/>
    password:<input type="password" id="password" name="password"/><br>
    verification_code:<input type="text" id="code" name="code"/><img id="code_img" style="position:relative;top:8px;height:25px"><br>
    <input type="button" id="btn" value="登录"/>
   </form>
  </body>
</html>

成功页面就部贴出来了,就是一段文字而已
显示结果:

Java实现验证码具体代码