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>

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值