web.xml
<servlet>
<description></description>
<display-name>ValidateImgServlet</display-name>
<servlet-name>ValidateImgServlet</servlet-name>
<servlet-class>com.web.servlet.ValidateImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateImgServlet</servlet-name>
<url-pattern>/validateimg.jpg</url-pattern>
</servlet-mapping>
ValidateImgServlet.java
package com.web.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.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
@SuppressWarnings ( "restriction" )
public class ValidateImgServlet extends HttpServlet implements Servlet
{
/**
* 中文4字验证码
*/
private static final long serialVersionUID = 1L;
// 设置图片的长宽
private int width = 130;
private int height = 30;
//设定被随机选取的中文字,此处中文字内容过多,不一一列出,只是举例说明下。
private String base ="\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u538b\u6162\u53d4\u80cc\u7ec6";
//设置随机 备选的字体类型
private String[] fontTypes = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
response.setContentType( "image/jpeg" );
//设置 备选随机汉字的个数
int length = base.length();
//设置随机 备选字体的个数
int fontTypesLength = fontTypes.length;
// 创建随机函数的实例
Random random = new Random();
//创建缓存图片
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
Graphics g = image.getGraphics();
//此处 设定图像背景色
g.setColor( getRandColor( random, 188, 235 ) );
g.fillRect( 0, 0, width, height );
// 在图片背景上增加噪点,增加图片分析难度
g.setColor( getRandColor( random, 180, 199 ) );
g.setFont( new Font( "Times New Roman", Font.PLAIN, 14 ) );
for ( int i = 0; i < 4; i++ )
{
g.drawString( "@*@*@*@*@*@*@*",0, 5 * ( i + 2 ) );
}
// 取随机产生的验证码 (4 个汉字 )
// 保存生成的汉字字符串
String sRand = "";
for ( int i = 0; i < 4; i++ )
{
int start = random.nextInt( length );
String rand = base.substring( start, start + 1 );
sRand += rand;
// 设置图片上字体的颜色
g.setColor( getRandColor( random, 10, 150 ) );
// 设置字体格式
g.setFont( new Font( fontTypes[random.nextInt( fontTypesLength )],
Font.BOLD, 18 + random.nextInt( 6 ) ) );
// 将此汉字画到验证图片上面
g.drawString( rand, 24 * i + 10 + random.nextInt( 8 ), 24 );
}
//将验证码记录在session中,便于用户输入之后的验证
request.getSession().setAttribute("ValidateCode", sRand);
g.dispose();
//输出图片
ServletOutputStream outStream = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder( outStream );
encoder.encode( image );
outStream.close();
}
//在此处 获取并生成随机颜色
private Color getRandColor( Random random, int ff, int cc )
{
if ( ff > 255 )
ff = 255;
if ( cc > 255 )
cc = 255;
int r = ff + random.nextInt( cc - ff );
int g = ff + random.nextInt( cc - ff );
int b = ff + random.nextInt( cc - ff );
return new Color( r, g, b );
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>hello word</title>
</head>
<script type="text/javascript">
//是否取cook里保存的用户名
var isPostBack = true;
//GUID标识符
var id = "49BAC005-7D5B-4231-8CEA-16939BEACD67";
window.οnlοad=function onLoginLoaded()
{
if (isPostBack) {
GetLastUser();
}
}
function GetLastUser()
{
var usr = GetCookie(id);
if (usr != null)
{
//取到值时
document.getElementById('txtUserName').value = usr;
}
else
{
}
}
//点击登录时触发客户端事件
function SetPwdAndChk()
{
//取用户名
var usr = document.getElementById('txtUserName').value;
var checkUser = document.getElementById('chkRememberUser').checked;
if(checkUser)
{
//将最后一个用户信息写入到Cookie
SetLastUser(usr);
}
else
{
//如果没有选中记住,则立即过期
ResetCookie(id);
}
//提交验证
}
function SetLastUser(usr)
{
var expdate = new Date();
//当前时间加上两周的时间
expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000));
SetCookie(id, usr, expdate);
}
//取Cookie的值
function GetCookie(name)
{
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen)
{
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
//获取cookie里面的值
function getCookieVal(offset)
{
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
//写入到Cookie
function SetCookie(name, value, expires)
{
var argv = SetCookie.arguments;
//本例中length = 3
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}
//情况cookie里的特定的值
function ResetCookie(val)
{
var expdate = new Date();
SetCookie(val, null, expdate);
}
</script>
<body>
<form name="login_form" method="post" action="login.action">
<div style="margin:100px 100px 100px 100px;">
<table align="center">
<tr align="center">
<td colspan="2">请输入登录信息</td>
</tr>
<tr align="left">
<td>用户名称:</td>
<td><input type="text" ID="txtUserName" style="width:120px;" /></td>
</tr>
<tr align="left">
<td>用户密码:</td>
<td><input type="password" ID="txtPassword" style="width:120px;"/></td>
</tr>
<tr align="left">
<td>验证码:</td>
<td><input type="text" name="validatecode" style="width:60px;" maxlength="5" /><a><img src="validateimg.jpg" border="0" /></a></td>
</tr>
<tr>
<td>记住账号:</td>
<td>
<input type="checkbox" ID="chkRememberUser" />
</td>
</tr>
<tr align="center">
<td colspan="2"><input type="button" OnClick="SetPwdAndChk()" value="登录"/>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>