源代码如下:

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 alt="" 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
[java] view plain copy
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();
}
}

2017.11.29 JSP+Servlet 中功能验证码及验证的实现的更多相关文章

  1. JSP/Servlet 中的汉字编码问题

    JSP/Servlet 中的汉字编码问题 1.问题的起源 每个国家(或区域)都规定了计算机信息交换用的字符编码集,如美国的 ASCII,中国的 GB2312 -80,日本的 JIS 等,作为该国家/区 ...

  2. JSP/Servlet 中的事件处理

    写过AWT或Swing程序的人一定对桌面程序的事件处理机制印象深刻:通过实现Listener接口的类可以在特定事件(Event)发生时,呼叫特定的方法来对事件进行响应. 其实我们在编写JSP/Serv ...

  3. servlet中生成验证码

    在servlet中生成验证码 package login; import java.awt.Color; import java.awt.Graphics; import java.awt.image ...

  4. JSP+Servlet中使用jspsmartupload.jar进行图片上传下载

    JSP+Servlet中使用cos.jar进行图片上传 upload.jsp <form action="FileServlet" method="post&quo ...

  5. JSP+Servlet中使用cos.jar进行图片上传(文件上传亦然)

    链接:JSP+Servlet中使用jspsmartupload.jar进行图片上传下载 关于cos.jar,百度百科只有这么几句话(http://baike.baidu.com/subview/406 ...

  6. 2017.11.27 用Servlet在JSP中加入验证码

    登陆界面 <%@ page pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ...

  7. jsp/servlet中的编码问题

    首先声明以下只是我个人的看法,有部分观点与网上人云亦云的观点不一样,不过凡事必恭亲,我还是相信自己测试的结果 推荐一个很好地URL编码详解http://www.ruanyifeng.com/blog/ ...

  8. JSP Servlet中的Request和Response的简单研究

    本文参考了几篇文章所得,参考目录如下: 1.http://www.cnblogs.com/guangshan/p/4198418.html 2.http://www.iteye.com/problem ...

  9. JSP Servlet中Request与Response所有成员方法的研究

    HttpServletRequest与HttpServletResponse作为Servlet中doGet.doPost等方法中传递的参数,承接了Http请求与响应中的大部分功能,请求的解析与响应的返 ...

随机推荐

  1. Autel MaxiSys Pro Description

    Autel MaxiSys pro MS908P is an evolutionary smart solution for specialized automotive diagnosis and ...

  2. Vuejs 实现权限管理

    程序运行时,router只配置登陆 首页404 等基本页面 import Main from '@/views/Main.vue'; // 不作为Main组件的子页面展示的页面单独写,如下 expor ...

  3. 20篇关于商品管理系统和uml技术的相关文献

    1.基于UML技术的商品管理系统设计与实现 2.UML技术在行业资源平台系统建模中的应用 3.基于JSP的商品信息管理系统设计与开发 4.基于UML技术的客户关系管理系统实现 5.商品管理系统 6.基 ...

  4. ES6多行字符串+模板字符串

    多行字符串 最新的ES6标准新增了一种多行字符串的表示方法,用反引号 ` ... ` 表示: 'use strict'; // 如果浏览器支持模板字符串,将会替换字符串内部的变量: var name ...

  5. ASC19超算概述

    初赛题目组成 设计超算集群(看参考文献做设计) 对超算集群进行性能测试(一般来讲的测试工具就是用HPL,找到最适合的参数,达到最优秀的计算能力) 数字图像处理(通常代码量较大,代码优化较为困难,优化偏 ...

  6. pyplot

    错误: 执行 import matplotlib.pyplot 报错 ImportError: No module named _tkinter, please install the python- ...

  7. (转)shell解析命令行的过程以及eval命令

    shell解析命令行的过程以及eval命令   本文说明的是一条linux命令在执行时大致要经过哪些过程?以及这些过程的大致顺序. 1.1 shell解析命令行 shell读取和执行命令时的大致操作过 ...

  8. C#读写txt文件的方法

    1.添加命名空间 System.IO; System.Text; 2.文件的读取 #region 读取TXT文本文件 /// <summary> /// FileStream读取文本文件 ...

  9. HBase Shell基本使用总结

    创建一个表 hbase(main):002:0> create 'member', 'cf_tmp', 'address', 'info' 查看所有表清单 hbase(main):003:0&g ...

  10. springboot从入门到精通(一)

    springboot到底有什么好处?有什么优势?这个先不用看,我们只要知道它有很多优势,现在要做的事只有一件,那就是撸代码!撸完就知道有多少料! 首先,在案例中,我们会构建一个英雄列表应用.操作如下: ...