现在的位置: 首页 > 综合 > 正文

Java+Servlet+Jsp实现验证码

2018年01月30日 ⁄ 综合 ⁄ 共 3836字 ⁄ 字号 评论关闭

实现验证码也很简单,就那么几个步骤,理解就好!


下面是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%>">    
    <title>登录</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">
	-->			
  </head> 
<body>

   <form action="user?types=login" method="post">
   <div>
	   <label>用户登陆:</label>
	   <input type="text" value="" maxlength="100" id="username"name="username">    
  </div>
  
  <div>
	   <label>登陆密码:</label>
	   <input type="password" value="" maxlength="100" id="password" name="password">   
  </div>
 
  <div>
	   <label>验证码</label>
	   <input type="text" value="" maxlength="100" id="yzm" name="veryCode" >

           <!--重要的是下面这一段代码。通过JavaScript的时间函数Date().getTime(),就可以实现点击验证码图片的时候切换图片-->
       <div><a href="javascript:document.getElementById('chkcode').src='imageCode.code?rnd='
+new Date().getTime();"><img src="imageCode.code" id="chkcode"/></a></div>
       
  </div>
  
  <div >
	   <input type="submit" value="提交" tabindex="4" id="send-btn"> 
  </div> 
  </form> 
</body>
</html>

下面是web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 

<servlet>
    <servlet-name>ValidateCode</servlet-name>
    <servlet-class>org.Public.util.ValidateCode</servlet-class><!--Servlet类的路径-->
  </servlet>


<servlet-mapping>
    <servlet-name>ValidateCode</servlet-name>
    <url-pattern>/imageCode.code</url-pattern>
  </servlet-mapping>

</web-app>


下面是Servlet:

package org.Public.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 生成验证码的工具类
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class ValidateCode extends HttpServlet {

	private static final int WIDTH = 120;
	private static final int HEIGHT = 35;

	
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 创建一个BufferedImage类的对象
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		// 创建一个Graphics类的对象
		Graphics graphics = image.getGraphics();
		// 设置画笔的颜色
		graphics.setColor(Color.BLUE);
		// 画一个矩形方框
		graphics.drawRect(0, 0, WIDTH, HEIGHT);
		// 设置画笔的颜色
		graphics.setColor(Color.GREEN);
		// 填充矩形的背景色
		graphics.fillRect(1, 1, WIDTH - 2, HEIGHT - 2);

		// 画干扰线
		graphics.setColor(Color.RED);
		Random random = new Random();
		for (int i = 0; i < 5; i++) {
			graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT),
					random.nextInt(WIDTH), random.nextInt(HEIGHT));
		}

		// 画数字
		// 设置字体大小
		Font font = new Font("宋体", Font.ITALIC, 24);
		graphics.setFont(font);
		graphics.setColor(Color.BLUE);
		int x = 10;
		char[] ch = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
				'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
				'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
				'H', 'I', 'G', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
				'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

		StringBuffer buffer = new StringBuffer();

		for (int i = 0; i < 4; i++) {
			int tempNum = random.nextInt(10);
			if (tempNum < 5) {
				// 若果随机数小于5,就画一个数字
				String param1 = random.nextInt(10) + "";
				graphics.drawString(param1, x, 20);
				x += 30;
				buffer.append(param1);
			} else {
				// 随机数大于5就画一个字母
				String param2 = String.valueOf(ch[random.nextInt(52)]);
				graphics.drawString(param2, x, 20);
				x += 30;
				buffer.append(param2);
			}
		}

		// 取得当前的session对象
		HttpSession session = request.getSession();
		// 将这个buffer对象添加到session域中
		session.setAttribute("photoCode", buffer.toString());

		// 设置客户端不要缓存
		response.setHeader("Expires", "1");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");

		
		// 输出到客户端
		ImageIO.write(image, "jpeg", response.getOutputStream());
		
		
	}

}


抱歉!评论已关闭.