有段时间没发贴了,下午抽了点时间,做个小东西。分享源码了。
使用技术Servlet+Ajax,开发环境:intellij(换个新环境玩玩)
实现无刷新验证验证码,更换验证码。很简单的功能,如果能搞的话,就Alt+F4吧。面向新手的。
相关源码:
页面img3.html
<!
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< title > 验证码 </ title >
< script type ="text/javascript" src ="jslib/jquery-1.2.6.min.js" ></ script >
</ head >
< body >
< script type ="text/javascript" >
function changeImg(){
var url = " Image3Servlet " ;
url = convertURL(url);
document.getElementById( " image " ).src = url;
}
function convertURL(url){
var timetamp = ( new Date()).valueOf();
url = url + " ?t= " + timetamp;
return url;
}
</ script >
< script type ="text/javascript" >
function validation(){
$.get( " ValServlet?checkcode= " + $( " #checkcode " ).val(), null ,callback);
}
function callback(data){
var resultObj = $( " #result " );
resultObj.html(data);
}
</ script >
< table >
< tr >
< td > 输入验证码: </ td >
< td >
< input type ="text" id ="checkcode" size ="10" maxlength ="10" >
< img src ="Image3Servlet" id ="image" />
< a href ="javascript:changeImg();" title ="更换一张验证码图片" > 看不清,换一张 </ a >
</ td >
</ tr >
< tr >< td colspan ="2" > < input type ="button" onclick ="validation()" value ="提交" />
</ td >
</ tr >
</ table >
< div id ="result" ></ div >
</ body >
</ html >
"http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< title > 验证码 </ title >
< script type ="text/javascript" src ="jslib/jquery-1.2.6.min.js" ></ script >
</ head >
< body >
< script type ="text/javascript" >
function changeImg(){
var url = " Image3Servlet " ;
url = convertURL(url);
document.getElementById( " image " ).src = url;
}
function convertURL(url){
var timetamp = ( new Date()).valueOf();
url = url + " ?t= " + timetamp;
return url;
}
</ script >
< script type ="text/javascript" >
function validation(){
$.get( " ValServlet?checkcode= " + $( " #checkcode " ).val(), null ,callback);
}
function callback(data){
var resultObj = $( " #result " );
resultObj.html(data);
}
</ script >
< table >
< tr >
< td > 输入验证码: </ td >
< td >
< input type ="text" id ="checkcode" size ="10" maxlength ="10" >
< img src ="Image3Servlet" id ="image" />
< a href ="javascript:changeImg();" title ="更换一张验证码图片" > 看不清,换一张 </ a >
</ td >
</ tr >
< tr >< td colspan ="2" > < input type ="button" onclick ="validation()" value ="提交" />
</ td >
</ tr >
</ table >
< div id ="result" ></ div >
</ body >
</ html >
验证码生成的servlet,生成字母加数字的四位验证码。
Image3Servlet
package
com.sy.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.Date;
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 Image3Servlet extends HttpServlet {
// Process the HTTP Get request
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 );
// 设置图片的长宽
int width = 62 , height = 22 ;
// ////// 创建内存图像
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.createGraphics();
// 设定图像背景色(因为是做背景,所以偏淡)
g.setColor(getRandColor( 180 , 250 ));
g.fillRect( 0 , 0 , width, height);
// 设置字体
g.setFont( new Font( " Times New Roman " , Font.BOLD, 18 ));
// //// /设置默认生成4个验证码
int length = 4 ;
java.util.Random rand = new Random(); // 设置随机种子
/*
* if (request.getParameter("length") != null) { try { length =
* Integer.parseInt(request.getParameter("length")); }catch
* (NumberFormatException e) {} }
*/
// 设置备选验证码:包括"a-z"和数字"0-9"
String base = " abcdefghijklmnopqrstuvwxyz0123456789 " ;
int size = base.length();
StringBuffer str = new StringBuffer();
for ( int i = 0 ; i < length; i ++ ) {
int start = rand.nextInt(size);
String tmpStr = base.substring(start, start + 1 );
str.append(tmpStr);
// 生成随机颜色(因为是做前景,所以偏深)
g.setColor(getRandColor( 10 , 150 ));
// 将此字画到图片上
// g.drawString(str.toString(), 4, 17);
g.drawString(tmpStr, 13 * i + 6 + rand.nextInt( 5 ), 14 + rand
.nextInt( 6 ));
}
// 将认证码存入session
request.getSession().setAttribute( " validationCode " , str.toString());
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, " JPEG " , response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this .doGet(request, response);
}
// 给定范围获得一个随机颜色
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);
}
}
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
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 Image3Servlet extends HttpServlet {
// Process the HTTP Get request
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 );
// 设置图片的长宽
int width = 62 , height = 22 ;
// ////// 创建内存图像
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.createGraphics();
// 设定图像背景色(因为是做背景,所以偏淡)
g.setColor(getRandColor( 180 , 250 ));
g.fillRect( 0 , 0 , width, height);
// 设置字体
g.setFont( new Font( " Times New Roman " , Font.BOLD, 18 ));
// //// /设置默认生成4个验证码
int length = 4 ;
java.util.Random rand = new Random(); // 设置随机种子
/*
* if (request.getParameter("length") != null) { try { length =
* Integer.parseInt(request.getParameter("length")); }catch
* (NumberFormatException e) {} }
*/
// 设置备选验证码:包括"a-z"和数字"0-9"
String base = " abcdefghijklmnopqrstuvwxyz0123456789 " ;
int size = base.length();
StringBuffer str = new StringBuffer();
for ( int i = 0 ; i < length; i ++ ) {
int start = rand.nextInt(size);
String tmpStr = base.substring(start, start + 1 );
str.append(tmpStr);
// 生成随机颜色(因为是做前景,所以偏深)
g.setColor(getRandColor( 10 , 150 ));
// 将此字画到图片上
// g.drawString(str.toString(), 4, 17);
g.drawString(tmpStr, 13 * i + 6 + rand.nextInt( 5 ), 14 + rand
.nextInt( 6 ));
}
// 将认证码存入session
request.getSession().setAttribute( " validationCode " , str.toString());
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, " JPEG " , response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this .doGet(request, response);
}
// 给定范围获得一个随机颜色
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);
}
}
验证的servlet
package
com.sy.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
public class ValServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType( " text/html;charset=utf-8 " );
PrintWriter out = response.getWriter();
String checkcode = request.getParameter( " checkcode " );
if (checkcode == null || checkcode.length() == 0 ){
out.println( " 验证码不能为空 " );
} else {
if (checkcode.equals(request.getSession().getAttribute( " validationCode " ))){
out.println( " 验证码输入正确 " );
} else {
out.println( " 验证码输入错误 " );
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
public class ValServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType( " text/html;charset=utf-8 " );
PrintWriter out = response.getWriter();
String checkcode = request.getParameter( " checkcode " );
if (checkcode == null || checkcode.length() == 0 ){
out.println( " 验证码不能为空 " );
} else {
if (checkcode.equals(request.getSession().getAttribute( " validationCode " ))){
out.println( " 验证码输入正确 " );
} else {
out.println( " 验证码输入错误 " );
}
}
} catch (Exception e){
e.printStackTrace();
}
}
}
web.xml这种简单的配置就不贴出来了,太简单了。
本文转自施杨博客园博客,原文链接:http://www.cnblogs.com/shiyangxt/archive/2008/12/12/1353854.html,如需转载请自行联系原作者