<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>  

 <%
String action = request.getParameter("action");
String safecodeText = request.getParameter("safecodeTest");
if("action".equals(action)){
String safecode = (String)session.getAttribute("safecode");
if(safecode.equals(safecodeText)){
out.print("验证码正确!");
}else{
out.print("验证码错误!请重新输入!");
}
}
%>
<html>
<head>
<title>验证码测试</title>
</head> <body>
<form action="servlet/demo" method="post">
<input type="hidden" name="action" value="action"/>
<img alt="验证码" src="servlet/demo">
<input type="text" name="safecodeTest">
<input type="submit" value="go">
</form>
</body>
</html>
 import java.io.*;  

 import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Random;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*; public class demo extends HttpServlet {
//产生随即的字体
private Font getFont() {
Random random = new Random();
Font font[] = new Font[5];
font[0] = new Font("Ravie", Font.PLAIN, 24);
font[1] = new Font("Antique Olive Compact", Font.PLAIN, 24);
font[2] = new Font("Forte", Font.PLAIN, 24);
font[3] = new Font("Wide Latin", Font.PLAIN, 24);
font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 24);
return font[random.nextInt(5)];
} protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 设置响应头 Content-type类型
resp.setContentType("image/jpeg");
// 以下三句是用于设置页面不缓存
resp.setHeader("Pragma", "No-cache");
resp.setHeader("Cache-Control", "No-cache");
resp.setDateHeader("Expires", 0); OutputStream os = resp.getOutputStream();
int width = 83, height = 30;
// 建立指定宽、高和BufferedImage对象
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // 该画笔画在image上
Color c = g.getColor(); // 保存当前画笔的颜色,用完画笔后要回复现场
g.fillRect(0, 0, width, height); char[] ch = "abcdefghjkmnpqrstuvwxyz23456789".toCharArray(); // 随即产生的字符串 不包括 i l(小写L) o(小写O) 1(数字1)0(数字0)
int length = ch.length; // 随即字符串的长度
String sRand = ""; // 保存随即产生的字符串
Random random = new Random();
for (int i = 0; i <; i++) {
// 设置字体
g.setFont(getFont());
// 随即生成0-9的数字
String rand = new Character(ch[random.nextInt(length)]).toString();
sRand += rand;
// 设置随机颜色
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawString(rand, 20 * i + 6, 25);
}
//产生随即干扰点
for (int i = 0; i < 20; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
g.drawOval(x1, y1, 2, 2);
}
g.setColor(c); // 将画笔的颜色再设置回去
g.dispose(); //将验证码记录到session
req.getSession().setAttribute("safecode", sRand);
// 输出图像到页面
ImageIO.write(image, "JPEG", os); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
} }
 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JavaWebDemo</display-name>
<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>demo</servlet-name>
<servlet-class>demo</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/servlet/demo</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
 package action;

 import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Map; import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class ImageAction extends ActionSupport { /**
*
*/
private static final long serialVersionUID = 1L;
private ByteArrayInputStream inputStream;
public String createRandomString(){
String str="";
for(int i=0;i<4;i++){
str+=Integer.toString((new Double(Math.random()*10)).intValue());
}
return str;
}
public Color createRandomColor(){
int r=(new Double(Math.random()*256)).intValue();
int g=(new Double(Math.random()*256)).intValue();
int b=(new Double(Math.random()*256)).intValue();
return new Color(r,g,b);
}
public BufferedImage createImage(String str){
int width=60;
int height=22;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
g.setColor(this.createRandomColor());
g.drawString(Character.toString(str.charAt(0)), 8, 17);
g.drawString(Character.toString(str.charAt(1)), 20, 17);
g.drawString(Character.toString(str.charAt(2)), 33, 17);
g.drawString(Character.toString(str.charAt(3)), 45, 17);
g.dispose();
return image;
}
public ByteArrayInputStream createInputStream() throws Exception{
String str=this.createRandomString();
BufferedImage image=this.createImage(str);
ActionContext actioncontext=ActionContext.getContext();
Map session=actioncontext.getSession();
session.put("random", str);
ByteArrayOutputStream output=new ByteArrayOutputStream();
ImageOutputStream imageout=ImageIO.createImageOutputStream(output);
ImageIO.write(image, "JPEG", imageout);
imageout.close();
ByteArrayInputStream input=new ByteArrayInputStream(output.toByteArray());
output.close();
return input;
}
public String execute() throws Exception{
setInputStream(createInputStream());
return SUCCESS;
}
public ByteArrayInputStream getInputStream(){
return inputStream;
}
public void setInputStream(ByteArrayInputStream inputStream){
this.inputStream=inputStream;
}
}

利用servlet技术实现验证码功能的更多相关文章

  1. django验证码功能

    1.目的 现在我们一般访问网页都需要输入验证码,比如博客园,有的甚至是通过手机验证码实时登录.这样做的目的主要还是为了防止其他人的恶意访问,比如爬虫,下面就来看看验证码是如何实现的 2.StringI ...

  2. Servlet案例3:验证码功能

    这里介绍简单的验证码功能 动态生成图片 一个简单的页面: <!DOCTYPE html> <html> <head> <meta charset=" ...

  3. 利用PHP绘图函数实现简单验证码功能

    index.php __________________________________________________________________________________________ ...

  4. c#实现验证码功能

    一.验证码简介 验证码功能一般是用于防止批量注册的,不少网站为了防止用户利用机器人自动注册.登录.灌水,都采用了验证码技术.所谓验证码,就是将一串随机产生的数字或字母或符号或文字,生成一幅图片, 图片 ...

  5. javaweb实现验证码功能

    在javaweb的用户注册与登陆功能时,有时为了防止漏洞或者大量注册,可以使用验证码功能,下面是验证码的一个简单实现 验证码类 public class ValiImg extends HttpSer ...

  6. 用PHP实现验证码功能

    目前,不少网站为了防止用户利用机器人自动注册.登录.灌水,都采用了 验证码技术.所谓验证码,就是将一串随机产生的数字或符号,生成一幅图片, 图片里加上一些干扰象素(防止OCR),由用户肉眼识别其中的验 ...

  7. 用java来实现验证码功能(本帖为转载贴),作为个人学习收藏用

    一.关于为何使用验证的解释 在目前的网页的登录.注册中经常会见到各种验证码.其目的便是为了:防止暴力破解  .因为只要CPU性能较强,便可以在慢慢尝试密码的过程中来破解用户账号,因而导致的结果是用户信 ...

  8. c#实现验证码功能(多种模式下分别实现验证功能)详细,带注释

    网上找了很多验证相关的代码,发现有很多瑕疵.现在本人整理测试了一个实现验证码功能的代码,里面有纯数字,纯英文,英文和数字混合等三种模式.并且在必要地方都已经备有注释,希望可以帮到那些需要的人. 验证码 ...

  9. S2SH框架中的无刷新验证码功能实现

    暑假期间在实验室做使用S2SH框架的项目,其中登录和注册需要验证码,实现了一个没有实现刷新验证码功能的简单版本,代码如下: 1 package com.sem.action; 2 3 import j ...

随机推荐

  1. 转载-smarty教程(基本语法)

    转自:http://hi.baidu.com/qxxgvpdtzhbckpr/item/681049160d7be60db98a1aec 1.smarty的配置      首先,使用smarty第一件 ...

  2. NHibernate统一类封装代码

    NHibernate已经成为.net主流的ORM框架,当然,在开发中如果需要使用NHibernate的话,我们一般会对她进行一次封装,以便在项目中使用更方便,以及对NHibernate有一个全局的控制 ...

  3. 杨氏矩阵 leecode 提

    提交网址https://oj.leetcode.com/problems/search-a-2d-matrix/ 有个矩阵中的数,从左向右递增,从上而下递增,快速查找是一个数是是否存在,剑指offer ...

  4. HDU FatMouse's Speed 基本DP

    题意:要求找到的体重递增,速度递减的老鼠,并且输出最长的长度数,而且输出各自的序列数.Special Judge 思路:先按体重由小到大排序,再找最长速度递减序列. 转移方程:mou[i].w> ...

  5. weblogic启动时日志重定向(nohup.out)

    由于weblogic使用  nohup ./startWebLogic.sh &   启动时会将所有日志打印到nohup.out上,长此以往会导致该文件越来越大,不便于管理. 故下面介绍如何重 ...

  6. [一]初识Poi

    示例代码: package com.lxl.poi; import java.io.FileOutputStream; import org.apache.poi.hssf.usermodel.HSS ...

  7. maven依赖规则

    1.就近原则,传递依赖 A-B-C -> A-C 2.先声明原则 A-B-C D-E-C 依赖的规则阻止了jar包冲突

  8. 图像处理界的标准图像Lena背后的故事

    今天晚上实验室的哥们问到我:“蒋志强,你知道咱们数字图像处理界标准图像Lena吗?” “当然知道啊,不就是那个512×512的美丽姐姐的标准图像么?”我不以为然的回答: “那幅图像事实上不是原始图像? ...

  9. Delphi调用C++写的dll示例

    最近做一个读市民卡的项目,读卡器公司提供的读市民卡dll是用C++写的. 下面记录一些自己的心得,供需要的朋友参考. 声明dll函数要加上stdcall关键字,否则可能会报地址非法的错误. 代码: u ...

  10. sql语法:inner join on, left join on, right join on具体用法

    inner join(等值连接) 仅仅返回两个表中联结字段相等的行 left join(左联接) 返回包含左表中的全部记录和右表中联结字段相等的记录 right join(右联接) 返回包含右表中的全 ...