jsp验证码

<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
<%
// 在内存中创建图象
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);

// 获取图形上下文
Graphics g = image.getGraphics();

// 设定背景色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);

//画边框
g.setColor(Color.black);
g.drawRect(0,0,width-1,height-1);

// 取随机产生的认证码(4位数字)
String rand = request.getParameter("rand");
rand = rand.substring(0,rand.indexOf("."));
switch(rand.length())
{
case 1: rand = "000"+rand; break;
case 2: rand = "00"+rand; break;
case 3: rand = "0"+rand; break;
default: rand = rand.substring(0,4); break;
}

// 将认证码存入SESSION
session.setAttribute("rand",rand);

// 将认证码显示到图象中
g.setColor(Color.black);
Integer tempNumber = new Integer(rand);
String numberStr = tempNumber.toString();

g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
String Str = numberStr.substring(0,1);
g.drawString(Str,8,17);

Str = numberStr.substring(1,2);
g.drawString(Str,20,15);
Str = numberStr.substring(2,3);
g.drawString(Str,35,18);

Str = numberStr.substring(3,4);
g.drawString(Str,45,15);

// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
Random random = new Random();
for (int i=0;i<20;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x,y,0,0);
}

// 图象生效
g.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>

生成有4个随机数字和杂乱背景的图片,数字和背景颜色会改变,服务器端刷新(用history.go(-1)也会变)

产生验证码图片的文件image.jsp

<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
Color getRandColor(int fc,int bc){//给定范围获得随机颜色
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
        }
%>
<%
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

// 在内存中创建图象
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// 获取图形上下文
Graphics g = image.getGraphics();

//生成随机类
Random random = new Random();

// 设定背景色
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);

//设定字体
g.setFont(new Font("Times New Roman",Font.PLAIN,18));

//画边框
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);

// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
 int x = random.nextInt(width);
 int y = random.nextInt(height);
        int xl = random.nextInt(12);
        int yl = random.nextInt(12);
 g.drawLine(x,y,x+xl,y+yl);
}

// 取随机产生的认证码(4位数字)
String sRand="";
for (int i=0;i<4;i++){
    String rand=String.Of(random.nextInt(10));
    sRand+=rand;
    // 将认证码显示到图象中
    g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
    g.drawString(rand,13*i+6,16);
}

// 将认证码存入SESSION
session.setAttribute("rand",sRand);

// 图象生效
g.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>

 

使用验证码图片的文件a.jsp

<%@ page contentType="text/html;charset=gb2312" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>认证码输入页面</title>
< http-equiv="Content-Type" content="text/html; charset=gb2312">
< HTTP-EQUIV="Pragma" CONTENT="no-cache">
< HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
< HTTP-EQUIV="Expires" CONTENT="0">
</head>
<body>
<form method=post action="check.jsp">
<table>
<tr>
<td align=left>系统产生的认证码:</td>
<td><img border=0 src="/image.jsp"></td>
</tr>
<tr>
<td align=left>输入上面的认证码:</td>
<td><input type=text name=rand maxlength=4 =""></td>
</tr>
<tr>
<td colspan=2 align=center><input type=submit ="提交检测"></td>
</tr>
</form>
</body>
</html>

 

验证的页面check.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>认证码验证页面</title>
< http-equiv="Content-Type" content="text/html; charset=gb2312">
< HTTP-EQUIV="Pragma" CONTENT="no-cache">
< HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
< HTTP-EQUIV="Expires" CONTENT="0">
</head>

<body>
<%
 String rand = (String)session.getAttribute("rand");
 String input = request.getParameter("rand");
%>
系统产生的认证码为: <%= rand %><br>
您输入的认证码为: <%= input %><br>
<br>
<%
  if (rand.equals(input)) {
%>
<font color=green>输入相同,认证成功!</font>
<%
  } else {
%>
<font color=red>输入不同,认证失败!</font>
<%
  }
%>
</body>
</html>

<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
<%
// 在内存中创建图象
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);

// 获取图形上下文
Graphics g = image.getGraphics();

// 设定背景色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);

//画边框
g.setColor(Color.black);
g.drawRect(0,0,width-1,height-1);

// 取随机产生的认证码(4位数字)
String rand = request.getParameter("rand");
rand = rand.substring(0,rand.indexOf("."));
switch(rand.length())
{
case 1: rand = "000"+rand; break;
case 2: rand = "00"+rand; break;
case 3: rand = "0"+rand; break;
default: rand = rand.substring(0,4); break;
}

// 将认证码存入SESSION
session.setAttribute("rand",rand);

// 将认证码显示到图象中
g.setColor(Color.black);
Integer tempNumber = new Integer(rand);
String numberStr = tempNumber.toString();

g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
String Str = numberStr.substring(0,1);
g.drawString(Str,8,17);

Str = numberStr.substring(1,2);
g.drawString(Str,20,15);
Str = numberStr.substring(2,3);
g.drawString(Str,35,18);

Str = numberStr.substring(3,4);
g.drawString(Str,45,15);

// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
Random random = new Random();
for (int i=0;i<20;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x,y,0,0);
}

// 图象生效
g.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>

另外一种:
生成验证码文件:
<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
    Color getRandColor(int fc,int bc)
{
    Random random = new Random();
    if(fc>255) fc=255;
    if(bc>255) bc=255;
    int r=fc+random.nextInt(bc-fc);
    int g=fc+random.nextInt(bc-fc);
    int b=fc+random.nextInt(bc-fc);
    return new Color(r,g,b);
    }
%>
<%
out.clear();//这句针对resin服务器,如果是tomacat可以不要这句
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


Graphics g = image.getGraphics();
Random random = new Random();

g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);

g.setFont(new Font("Times New Roman",Font.PLAIN,18));

 

g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
    int xl = random.nextInt(12);
    int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}


String sRand="";
for (int i=0;i<4;i++){
  String rand=String.Of(random.nextInt(10));
  sRand+=rand;

  g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
  g.drawString(rand,13*i+6,16);
}

// 将认证码存入SESSION
session.setAttribute("rand",sRand);

g.dispose();

ImageIO.write(image, "JPEG", response.getOutputStream());
%>

验证:
<%
   //读取提交的表单内容
   String rand=(String)session.getAttribute("rand");
   String input=request.getParameter("rand");
   if (rand.equals(input))
   {
    response.sendRedirect("success.jsp");
   }
   else
   {
    .....
    }

%>
html代码自己写

servlet验证码程序
/*
*生产随机显示的验证码图片
*
*/
package webutil;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
import java.util.Random;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
//import com.sun.image.codec.jpeg.*;

public class VImage extends HttpServlet
{
    public void init(ServletConfig conf) throws ServletException
    {
        super.init(conf);
    }
    
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
    {
        res.setContentType("image/jpeg");
        res.setHeader("Pragma","No-cache");
        res.setHeader("Cache-Control","no-cache");
        res.setDateHeader("Expires", 0);
        HttpSession session = req.getSession();
        
        // 在内存中创建图象
        int width=86, height=20;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        
        // 获取图形上下文
        Graphics g = image.getGraphics();
        
        // 生成随机类
        Random random = new Random();
        
        // 设定背景色
        g.setColor(getRandColor(200,250));
        g.fillRect(0, 0, width, height);
        
        // 设定字体
        g.setFont(new Font("Times New Roman",Font.PLAIN,18));
        
        // 画边框
        //g.setColor(new Color());
        //g.drawRect(0,0,width-1,height-1);
        
        // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
        g.setColor(getRandColor(160,200));
        for (int i=0;i<155;i++)
        {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x,y,x+xl,y+yl);
        }
     String rstr = "";
     RandomStrg rst = new RandomStrg();
     rst.setCharset("a-zA-Z0-9");
     rst.setLength("6");

     try {
     rst.generateRandomObject();
     rstr = rst.getRandom();

     } catch (Exception ex) {
     ex.printStackTrace();

     }
        
        // 取随机产生的认证码(4位数字)
        String sRand="";
        sRand = rstr;
        for (int i=0;i<sRand.length();i++)
        {
//          String rand=String.Of(random.nextInt(10));
     String rand = String.Of(rstr.charAt(i));
//          sRand+=rand;
          // 将认证码显示到图象中
          g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
          g.drawString(rand,13*i+6,16);
        }
        
        // 将认证码存入SESSION
        session.setAttribute("post_validate_code",sRand);
        
        // 图象生效
        g.dispose();
        
        // 输出图象到页面
        ImageIO.write(image, "JPEG", res.getOutputStream());
        //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(res.getOutputStream());
        //encoder.encode(image);
    }
    
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
    {
        doGet(req,res);
    }
    
    //给定范围获得随机颜色
    private Color getRandColor(int fc,int bc)
    {
        Random random = new Random();
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        return new Color(r,g,b);
  }
}

//随机字符串bean


package mycollect;

import java.util.*;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

public class RandomStrg {

private String randomstr;
private boolean allchars = false;
//欠缺是8位字符串
private Integer length = new Integer(8);
private HashMap hmap;
private ArrayList lower = null;
private ArrayList upper = null;
private char[] single = null;
private int singlecount = 0;
private boolean singles = false;
private String algorithm = null;
private String provider = null;
private boolean secure = false;
private Random random = null;
private SecureRandom secrandom = null;

private final float getFloat() {
if (random == null)
return secrandom.nextFloat();
else
return random.nextFloat();
}

/**
* generate the Random object that will be used for this random number
* generator
*
*/
public final void generateRandomObject() throws Exception {

// check to see if the object is a SecureRandom object
if (secure) {
try {
// get an instance of a SecureRandom object
if (provider != null)
// search for algorithm in package provider
random = SecureRandom.getInstance(algorithm, provider);
else
random = SecureRandom.getInstance(algorithm);
} catch (NoSuchAlgorithmException ne) {
throw new Exception(ne.getMessage());
} catch (NoSuchProviderException pe) {
throw new Exception(pe.getMessage());
}
} else
random = new Random();
}

/**
* generate the random string
*
*/
private final void generaterandom() {

if (allchars)
for (int i = 0; i < length.int(); i++)
randomstr = randomstr + new Character((char)((int) 34 +
((int)(getFloat() * 93)))).toString();
else if (singles) {
// check if there are single chars to be included

if (upper.size() == 3) {
// check for the number of ranges max 3 uppercase lowercase digits

// build the random string
for (int i = 0; i < length.int(); i++) {
// you have four groups to choose a random number from, to make
// the choice a little more random select a number out of 100

// get a random number even or odd
if (((int) (getFloat() * 100)) % 2 == 0) {

// the number was even get another number even or odd
if (((int) (getFloat() * 100)) % 2 == 0)
// choose a random char from the single char group
randomstr = randomstr + randomSingle().toString();
else
// get a random char from the first range
randomstr = randomstr + randomChar((Character)lower.get(2),
(Character)upper.get(2)).toString();
} else {
// the number was odd

if (((int) (getFloat() * 100)) % 2 == 0)
// choose a random char from the second range
randomstr = randomstr + randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
else
// choose a random char from the third range
randomstr = randomstr + randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
} else if (upper.size() == 2) {
// single chars are to be included choose a random char from
// two different ranges

// build the random char from single chars and two ranges
for (int i = 0; i < length.int(); i++) {
// select the single chars or a range to get each random char
// from

if (((int)(getFloat() * 100)) % 2 == 0) {

// get random char from the single chars
randomstr = randomstr + randomSingle().toString();
} else if (((int) (getFloat() * 100)) % 2 == 0) {

// get the random char from the first range
randomstr = randomstr + randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
} else {

// get the random char from the second range
randomstr = randomstr + randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
} else if (upper.size() == 1) {

// build the random string from single chars and one range
for (int i = 0; i < length.int(); i++) {
if (((int) getFloat() * 100) % 2 == 0)
// get a random single char
randomstr = randomstr + randomSingle().toString();
else
// get a random char from the range
randomstr = randomstr + randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
} else {
// build the rand string from single chars
for (int i = 0; i < length.int(); i++)
randomstr = randomstr + randomSingle().toString();
}
} else {

// no single chars are to be included in the random string
if (upper.size() == 3) {

// build random strng from three ranges
for (int i = 0; i < length.int(); i++) {

if (((int) (getFloat() * 100)) % 2 == 0) {

// get random char from first range
randomstr = randomstr + randomChar((Character)lower.get(2),
(Character)upper.get(2)).toString();
} else if (((int) (getFloat() * 100)) % 2 == 0) {

// get random char form second range
randomstr = randomstr + randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
} else {

// get random char from third range
randomstr = randomstr + randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}
} else if (upper.size() == 2) {

// build random string from two ranges
for (int i = 0; i < length.int(); i++) {
if (((int) (getFloat() * 100)) % 2 == 0)
// get random char from first range
randomstr = randomstr + randomChar((Character)lower.get(1),
(Character)upper.get(1)).toString();
else
// get random char from second range
randomstr = randomstr + randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
} else

// build random string
for (int i = 0; i < length.int(); i++)
// get random char from only range
randomstr = randomstr + randomChar((Character)lower.get(0),
(Character)upper.get(0)).toString();
}
}

/**
* generate a random char from the single char list
*
* @returns - a randomly selscted character from the single char list
*
*/
private final Character randomSingle() {

return (new Character(single[(int)((getFloat() * singlecount) - 1)]));
}

/**
* generate a random character
*
* @param lower lower bound from which to get a random char
* @param upper upper bound from which to get a random char
*
* @returns - a randomly generated character
*
*/
private final Character randomChar(Character lower, Character upper) {
int tempval;
char low = lower.char();
char up = upper.char();

// get a random number in the range lowlow - lowup
tempval = (int)((int)low + (getFloat() * ((int)(up - low))));

// return the random char
return (new Character((char) tempval));
}

/**
* get the randomly created string for use with the
* &lt;jsp:getProperty name=<i>"id"</i> property="randomstr"/&gt;
*
* @return - randomly created string
*
*/

public final String getRandom() {

randomstr = new String();

generaterandom(); // generate the first random string

if (hmap != null) {

while (hmap.containsKey(randomstr)) {
// random string has already been created generate a different one
generaterandom();
}

hmap.put(randomstr, null); // add the new random string
}

return randomstr;
}

/**
* set the ranges from which to choose the characters for the random string
*
* @param low set of lower ranges
* @param up set of upper ranges
*
*/
public final void setRanges(ArrayList low, ArrayList up) {
lower = low;
upper = up;
}


/**
* set the hashmap that is used to check the uniqueness of random strings
*
* @param map hashmap whose keys are used to insure uniqueness of random strgs
*
*/
public final void setHmap(HashMap map) {
hmap = map;
}

/**
* set the length of the random string
*
* @param length of the random string
*
*/
public final void setLength(String ) {
length = new Integer();

}

/**
* set the algorithm name
*
* @param name of the algorithm to use for a SecureRandom object
*
*/
public final void setAlgorithm(String ) {
algorithm = ;
secure = true; // a SecureRandom object is to be used
}

/**
* set the provider name
*
* @param name of the package to check for the algorithm
*
*/
public final void setProvider(String ) {
provider = ;
}

/**
* set the allchars flag
*
* @param boolean of the allchars flag
*
*/
public final void setAllchars(boolean ) {
allchars = ;
}

/**
* set the array of single chars to choose from for this random string and the
* number of chars in the array
*
* @param chars the array of single chars
* @param the number of single chars
*
*/
public final void setSingle(char[] chars, int ) {
single = chars; // set the array of chars
singlecount = ; // set the number of chars in array single
singles = true; // set flag that single chars are in use
}

public final void setCharset(String )
{
// s tells the method whether or not to check for single chars
boolean more = true;

// create the arraylists to hold the upper and lower bounds for the char
// ranges
lower = new ArrayList(3);
upper = new ArrayList(3);

// user has chosen to use all possible characters in the random string
if (.compareTo("all") == 0) {
allchars = true; // set allchars flag
// all chars are to be used so there are no single chars to sort
// through
more = false;
}else if ((.charAt(1) == '-') && (.charAt(0) != '\\')) {
// run through the ranges at most 3
while (more && (.charAt(1) == '-')){

// check to make sure that the dash is not the single char
if (.charAt(0) == '\\')
break;
else {
// add upper and lower ranges to there list
lower.add(new Character(.charAt(0)));
upper.add(new Character(.charAt(2)));
}

// check to see if there is more to the charset
if (.length() <= 3)
more = false;
else
// create a new string so that the next range if there is one
// starts it
= .substring(3);
}
}

// if more = false there are no single chars in the charset
if (more) {

single = new char[30]; // create single

// create a set of tokens from the string of single chars
StringTokenizer tokens = new StringTokenizer();

while (tokens.hasMoreTokens()) {
// get the next token from the string
String token = tokens.nextToken();

if (token.length() > 1)
// char is a - add it to the list
single[singlecount++] = '-';

// add the current char to the list
single[singlecount++] = token.charAt(0);
}
}
if ((lower == null) && (single == null))
setCharset("a-zA-Z0-9");
}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值