jsp+Servlet验证码及验证

一个用jsp+Servlet+jquery+ajax实现的验证码,及验证是否正确。供初学者学习交流。

效果图:

源代码:

validate.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">
<style type="text/css">
.error{
 background: url(./images/invalid_line.gif) repeat-x bottom;
 border: 1px solid red;
}
</style>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript">
$(function(){
 $("#check").blur(function(){
  $.ajax({
   type:‘post‘,
   url:‘check‘,
   data: {input: $(this).val()},
   dataType: "text/json",
   success: function(msg){
    var ret = eval(‘(‘ + msg + ‘)‘);
    var success = ret.success;
    $("#tip").html(ret.message);
    
    if(!success){
     $(this).val(‘‘);
     $("#image").attr(‘src‘,"validate?random="+Math.random());
     $("#check").addClass("error");
     $("#tip").css({‘color‘:‘red‘,‘font-family‘: ‘华文楷体‘});
    }else{
     $("#check").removeClass("error");
     $("#tip").css({‘color‘:‘black‘,‘font-family‘: ‘华文楷体‘});
    }
   }
  });
 });
 
 $("#image").click(function(){
  $(this).attr(‘src‘,"validate?random="+Math.random());
 });
});
</script>
</head>
<body>
 <input type="text" id="check" value="">
 <div id="tip">&nbsp;</div>
 <br>
 <img  src="validate" id="image">
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 version="2.5"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet-mapping>
  <servlet-name>validate</servlet-name>
  <url-pattern>/validate</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>validate</servlet-name>
  <servlet-class>test.MyValidateServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>check</servlet-name>
  <url-pattern>/check</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>check</servlet-name>
  <servlet-class>test.CheckServlet</servlet-class>
 </servlet>
</web-app>

ValidateCode.java

package util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
public class ValidateCode {
 public static final int TYPE_NUM_ONLY = 0;
 public static final int TYPE_LETTER_ONLY = 1;
 public static final int TYPE_ALL_MIXED = 2;
 public static final int TYPE_NUM_UPPER = 3;
 public static final int TYPE_NUM_LOWER = 4;
 public static final int TYPE_UPPER_ONLY = 5;
 public static final int TYPE_LOWER_ONLY = 6;
 public static String generateTextCode(int type, int length, String exChars) {
  if (length <= 0) {
   return "";
  }
  StringBuffer code = new StringBuffer();
  int i = 0;
  Random r = new Random();
  switch (type) {
  case 0:
   while (i < length) {
    int t = r.nextInt(10);
    if ((exChars == null) || (exChars.indexOf(t) < 0)) {
     code.append(t);
     i++;
    }
   }
   break;
  case 1:
   while (i < length) {
    int t = r.nextInt(123);
    if (((t >= 97) || ((t >= 65) && (t <= 90)))
      && ((exChars == null) || (exChars.indexOf((char) t) < 0))) {
     code.append((char) t);
     i++;
    }
   }
   break;
  case 2:
   while (i < length) {
    int t = r.nextInt(123);
    if (((t < 97) && ((t < 65) || (t > 90)) && ((t < 48) || (t > 57)))
      || ((exChars != null) && (exChars.indexOf((char) t) >= 0)))
     continue;
    code.append((char) t);
    i++;
   }
   break;
  case 3:
   while (i < length) {
    int t = r.nextInt(91);
    if (((t >= 65) || ((t >= 48) && (t <= 57)))
      && ((exChars == null) || (exChars.indexOf((char) t) < 0))) {
     code.append((char) t);
     i++;
    }
   }
   break;
  case 4:
   while (i < length) {
    int t = r.nextInt(123);
    if (((t >= 97) || ((t >= 48) && (t <= 57)))
      && ((exChars == null) || (exChars.indexOf((char) t) < 0))) {
     code.append((char) t);
     i++;
    }
   }
   break;
  case 5:
   while (i < length) {
    int t = r.nextInt(91);
    if ((t >= 65)
      && ((exChars == null) || (exChars.indexOf((char) t) < 0))) {
     code.append((char) t);
     i++;
    }
   }
   break;
  case 6:
   while (i < length) {
    int t = r.nextInt(123);
    if ((t >= 97)
      && ((exChars == null) || (exChars.indexOf((char) t) < 0))) {
     code.append((char) t);
     i++;
    }
   }
  }
  return code.toString();
 }
 public static BufferedImage generateImageCode(String textCode, int width,
   int height, int interLine, boolean randomLocation, Color backColor,
   Color foreColor, Color lineColor) {
  BufferedImage bim = new BufferedImage(width, height, 1);
  Graphics g = bim.getGraphics();
  g.setColor(backColor == null ? getRandomColor() : backColor);
  g.fillRect(0, 0, width, height);
  Random r = new Random();
  if (interLine > 0) {
   int x = 0;
   int y = 0;
   int x1 = width;
   int y1 = 0;
   for (int i = 0; i < interLine; i++) {
    g.setColor(lineColor == null ? getRandomColor() : lineColor);
    y = r.nextInt(height);
    y1 = r.nextInt(height);
    g.drawLine(x, y, x1, y1);
   }
  }
  int fsize = (int) (height * 0.8D);
  int fx = height - fsize;
  int fy = fsize;
  g.setFont(new Font("Default", 0, fsize));
  for (int i = 0; i < textCode.length(); i++) {
   fy = randomLocation ? (int) ((Math.random() * 0.3D + 0.6D) * height)
     : fy;
   g.setColor(foreColor == null ? getRandomColor() : foreColor);
   g.drawString(String.valueOf(textCode.charAt(i)), fx, fy);
   fx = (int) (fx + fsize * 0.9D);
  }
  g.dispose();
  return bim;
 }
 public static BufferedImage generateImageCode(int type, int length,
   String exChars, int width, int height, int interLine,
   boolean randomLocation, Color backColor, Color foreColor,
   Color lineColor) {
  String textCode = generateTextCode(type, length, exChars);
  BufferedImage bim = generateImageCode(textCode, width, height,
    interLine, randomLocation, backColor, foreColor, lineColor);
  return bim;
 }
 private static Color getRandomColor() {
  Random r = new Random();
  Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
  return c;
 }
}

MyValidateServlet.java

package test;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
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;
import util.ValidateCode;
public class MyValidateServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  resp.setHeader("Pragma", "No-cache");// 设置响应头信息,告诉浏览器不要缓存此内容
  resp.setHeader("Cache-Control", "no-cache");
  resp.setDateHeader("Expire", 0);
  try {
   String textCode = ValidateCode.generateTextCode(
     ValidateCode.TYPE_ALL_MIXED, 6, null);
   BufferedImage image = ValidateCode.generateImageCode(textCode, 500,
     100, 5, true, Color.GRAY, null, null);
   HttpSession session = req.getSession(true);
   session.setAttribute("captcha", textCode);
   resp.setContentType("image/jpeg");
   OutputStream outputStream = resp.getOutputStream();
   ImageIO.write(image, "jpeg", outputStream);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

CheckServlet.java

package test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CheckServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  resp.setCharacterEncoding("UTF-8");
  resp.setContentType("text/html;chartset=UTF-8");
  req.setCharacterEncoding("UTF-8");
  String input = (String) req.getParameter("input");
  
  HttpSession sess = req.getSession();
  String captcha = (String) sess.getAttribute("captcha");
  PrintWriter out = resp.getWriter();
  if(input.toUpperCase().equals(captcha.toUpperCase())){
   out.print("{‘success‘: true,‘message‘: ‘验证码正确!‘}");
  }else{
   out.print("{‘success‘: false,‘message‘: ‘验证码错误!‘}");
  }
  
  out.flush();
  out.close();
 }
}
时间: 2024-08-25 01:24:26

jsp+Servlet验证码及验证的相关文章

Jsp+servlet 验证码案例

昨晚在csdn看到一位前辈写一个ajax+servlet+jsp验证.顿时心血来潮,在阅读前辈的代码下我亲手体验一下,做了一个验证码生成工具类.以供大家做个參考. 1:加入VeriyCodeUtils类生成验证码图像 package com.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import jav

JSP+Servlet实现验证码生成

主要利用JSP+Servlet实现验证码生成 利用JQuery的ajax技术实现异步更换图片地址 BufferedImage实现验证码图片的生成 Servlet代码: package Register; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOEx

Jsp制作验证码

验证码 验证码(CAPTCHA)是"Completely Automated Public Turing test to tell Computers and Humans Apart"(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序.可以防止:恶意破解密码.刷票.论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,实际上用验证码是现在很多网站通行的方式,我们利用比较简易的方式实现了这个功能.这个问题可以由计算

jsp servlet的区别和联系

简单的说,SUN首先发展出SERVLET,其功能比较强劲,体系设计也很先进,只是,它输出HTML语句还是采用了老的CGI方式,是一句一句输出,所以,编写和修改HTML非常不方便. 后来SUN推出了类似于ASP的镶嵌型的JSP,把JSP TAG镶嵌到HTML语句中,这样,就大大简化和方便了网页的设计和修改.新型的网络语言如ASP,PHP,JSP都是镶嵌型的SCRIPT语言. JSP在本质上就是SERVLET,但是两者的创建方式不一样. Servlet完全是JAVA程序代码构成,擅长于流程控制和事务

使用jsp生成验证码

在开发中验证码是比较常用到有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试的方式. 此演示程序包括三个文件: 1.index.jsp:登录页面 2.image.jsp:生成验证码图片页面 3.result.jsp:结果页面 [页面代码] 1.index.jsp <html> <body> <form method=post action="result.jsp"> <input type=text name=inpu

JSP/Servlet基础语法

相关学习资料 http://my.oschina.net/chape/blog/170247 http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/web_xml.html http://blog.csdn.net/liaoxiaohua1981/article/details/6761053 http://computer.c.blog.163.com/blog/static/102524482012314537670/ http://ww

jsp生成验证码

1 package servlet; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.Graphics; 6 import java.awt.image.BufferedImage; 7 import java.io.IOException; 8 import java.util.Random; 9 10 import javax.imageio.ImageIO; 11 import javax.servl

jsp+servlet+mysql 实现简单的银行登录转账功能

jsp+servlet+mysql 实现简单的银行登录转账功能 [前期的准备] html(登录界面),servlet(处理业务逻辑),jsp(主要实现界面),mysql(实现与数据库的简单的交互)先从一个登录页面开始(利用表单提交,action="jsp实现页面")第一步:在(mysql)数据库中建表:建立一个用户的基本信息表(用户姓名,密码,账户余额),用户转账(用户名,转账金额)的操作表第二步:登录页面:输入用户名和密码对数据库中的用户信息(login.jsp)进行验证(qq浏览器

【Servlet】Servlet简单登陆验证实例

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文要实现Servlet简单登陆验证实例.结构如下 1.LoginCheck.java package com.mucfc; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annota