一.js实现验证码:
第一步:建一个login.htm,一个code.js文件,一个code.css文件,准备一张图片code.jpg
第二步:编写login.htm文件,内容为:
- <html>
- <head>
- <script language = "javascript" src = "code.js"></script>
- <link rel="stylesheet" type="text/css" href="code.css">
- </head>
- <body onload="createCode();">
- <form>
- <center>验证码:<input type="text" id="input1" />
- <input type="text" id="checkCode" class="code" style="width: 55px" /> <a href="#" onclick="createCode()">看不清楚</a>
- <input id="Button1" onclick="validate();" type="button" value="确定" /></center>
- </form>
- </body>
- </html>
第三步:编写code.css文件,内容为:
- .code{
- background-image:url(code.jpg);
- font-family:Arial;
- font-style:italic;
- color:Red;
- border:0;
- padding:2px 3px;
- letter-spacing:3px;
- font-weight:bolder;
- }
第四步:编写code.js文件,内容为:
- var code ; //在全局 定义验证码
- function createCode(){
- code = "";
- var codeLength = 4;//验证码的长度
- var checkCode = document.getElementById("checkCode");
- checkCode.value = "";
- var selectChar = new Array(2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
- for(var i=0;i<codeLength;i++) {
- var charIndex = Math.floor(Math.random()*32);
- code +=selectChar[charIndex];
- }
- if(code.length != codeLength){
- createCode();
- }
- checkCode.value = code;
- }
- function validate () {
- var inputCode = document.getElementById("input1").value.toUpperCase();
- if(inputCode.length <=0) {
- alert("请输入验证码!");
- return false;
- }
- else if(inputCode != code ){
- alert("验证码输入错误!");
- createCode();
- return false;
- }
- else {
- alert("OK");
- return true;
- }
- }
第五步:把四个文件放到一个文件夹中,运行login.htm文件,显示结果为:
二.servlet实现验证码:
1.servlet内容
package com.yeshun.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
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;
public class RandCodeServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -7297771418249306891L;
public RandCodeServlet() {
super();
}
public void init() throws ServletException {
// Put your code here
}
public void destroy() {
super.destroy();
}
//数字验证码(4位)
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//设置页面不缓存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpg");
// 在内存中创建图象
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(33,66,99));
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.valueOf(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
request.getSession().setAttribute("randCode", sRand);
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//给定范围获得随机颜色
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);
}
/*
// 验证码1(6位带字母)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 在内存中创建图象
int width = 90, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 生成随机类
Random random = new Random();
// 设定背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 设定字体
g.setFont(new Font("Arial", Font.BOLD, 19));
// 画边框
// g.setColor(getRandColor(100, 250));
// g.drawRect(0, 0, width - 1, height - 1);
// 随机产生200条干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < 5; i++) {
g.setColor(getRandColor(100, 200));
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(5);
int yl = random.nextInt(5);
g.drawLine(x, y, x + xl, y + yl);
g.draw3DRect(x, y, xl, yl, false);
}
// 取随机产生的认证码(6位数字)
String sRand = "";
for (int i = 0; i < 6; i++) {
char rand = getRandomStr(random);
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand + "".toUpperCase(), 14 * i + 7, 16);
}
// 将认证码存入SESSION
request.getSession().setAttribute("randCode", sRand);
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
}
private char getRandomStr(Random random) {
char letters[] = "0123456789AaBbCcDdEeFfGgHhJjKkLMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
.toCharArray();
return letters[random.nextInt(36)];
}
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);
}
*/
/*
//验证码2(6位含字母)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
int width=100, height=18;
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(1, 1, width-1, height-1);
g.setColor(new Color(102,102,102));
g.drawRect(0, 0, width-1, height-1);
g.setFont(new Font("Arial Black", Font.PLAIN, 16));
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g.drawLine(x,y,x + xl,y + yl);
}
for (int i = 0;i < 70;i++)
{
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int xl = random.nextInt(12) + 1;
int yl = random.nextInt(6) + 1;
g.drawLine(x,y,x - xl,y - yl);
}
String sRand="";
for (int i=0;i<6;i++)
{
String tmp = getRandomChar();
sRand += tmp;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(tmp,15*i+10,15);
}
request.getSession().setAttribute("rand",sRand);
System.out.println(sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
}
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);
}
private String getRandomChar()
{
int rand = (int)Math.round(Math.random() * 2);
long itmp = 0;
char ctmp = '\u0000';
switch (rand)
{
case 1:
itmp = Math.round(Math.random() * 25 + 65);
ctmp = (char)itmp;
return String.valueOf(ctmp);
case 2:
itmp = Math.round(Math.random() * 25 + 97);
ctmp = (char)itmp;
return String.valueOf(ctmp);
default :
itmp = Math.round(Math.random() * 9);
return String.valueOf(itmp);
}
}
*/
}
2 编写login.jsp文件,内容为:
<script>
function refresh()
{
document.getElementById("authImg").src='servlet/randCode?now=' + new Date();
}
</script>
<body>
<img src="servlet/randCode" id="authImg" width="60" height="20">看不清?<a href="" onClick="refresh()">单击此处刷新</a> <br/>
</body>
3 在web.xml文件中配置代码,内容为:
<!-- 图片验证码 -->
<servlet>
<servlet-name>randCode</servlet-name>
<servlet-class>
com.yeshun.servlet.RandCodeServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>randCode</servlet-name>
<url-pattern>/servlet/randCode</url-pattern>
</servlet-mapping>