ndex.jsp
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" language="java" errorPage="" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax实现无刷新的彩色验证码</title>
<link rel="stylesheet" href="css/style.css" />
<script src="js/check.js"></script>
<script language="javascript" src="js/ajaxRequest.js"></script>
<script language="javascript">
function onerror(){
alert("您的操作有误!");
}
//生成并显示验证码
function getCheckCodeFun(showCheckCode,checkCode){
showCheckCode.style.display='';
if(document.getElementById("resultMessage").innerHTML=="温馨提示:单击验证码输入框,获取验证码!验证码区分大小写"){
getCheckCode1(showCheckCode,checkCode); //生成验证码
}
checkCode.focus();
}
//生成验证码
function getCheckCode1(showCheckCode,checkCode){
let loader1=new net.AjaxRequest("getPictureCheckCode.jsp?nocache="+new Date().getTime(),deal_getCheckCode,onerror,"GET");
showCheckCode.style.display='';
checkCode.focus();
}
function deal_getCheckCode(){
document.getElementById("showCheckCode").innerHTML=this.req.responseText;
}
//隐藏验证码显示框
function showCheckCodeClear(){
showCheckCode.style.display='none';
}
/***********验证验证码是否正确*******************************/
function checkCheckCode(inCheckCode){
if(inCheckCode!=""){
let loader=new net.AjaxRequest("checkCheckCode.jsp?inCheckCode="+inCheckCode+"&nocache="+new Date().getTime(),deal_checkCheckCode,onerror,"GET");
}
}
function deal_checkCheckCode(){
let h=this.req.responseText;
//去除字符串中的Unicode空白符
h=h.replace(/\s/g,"");
if(h==1){
document.getElementById("resultMessage").removeChild(document.getElementById("resultMessage").childNodes[0]);
document.getElementById("resultMessage").appendChild(document.createTextNode(" "));
document.getElementById("messageImg").src="images/dui2.gif";
document.getElementById("resultMessage").removeChild(document.getElementById("resultMessage").childNodes[0]);
document.getElementById("resultMessage").appendChild(document.createTextNode("恭喜您,验证码正确!"));
document.getElementById("btn_Submit").disabled=false;
}
else{
document.getElementById("messageImg").src="images/cuo2.gif";
document.getElementById("resultMessage").removeChild(document.getElementById("resultMessage").childNodes[0]);
document.getElementById("resultMessage").appendChild(document.createTextNode("您输入的验证码不正确!"));
}
}
</script>
</head>
<body onblur="showCheckCodeClear()">
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="22" background="images/bg_left.gif"> </td>
<td width="760">
<table width="760" height="646" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td height="126" align="center">
<%@include file="top.jsp"%>
</td>
</tr>
<tr>
<td height="446" valign="top">
<table width="100%" height="164" border="0" cellpadding="0" cellspacing="0" class="tableBorder_LRB">
<tr>
<td height="49" colspan="6" background="images/reply_navigate.gif"> </td>
</tr>
<tr>
<td width="5%" height="143" onClick="showCheckCodeClear()"> </td>
<td colspan="4" align="center" valign="top">
<form name="form1" method="post" action="">
<table width="100%" height="383" border="0" cellpadding="0" cellspacing="0">
<tr onClick="showCheckCodeClear()">
<td width="14%" height="36" align="center">留言人:</td>
<td colspan="3">
<input name="author" type="text" id="author" size="30" value="">
* </td>
</tr>
<tr onClick="showCheckCodeClear()">
<td height="107" align="center">表 情:</td>
<td colspan="3">
<input name="face" type=radio class="noborder" value=0 checked>
<img height=20
src="images/face/face0.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=1>
<img height=19
src="images/face/face1.gif" width=19 align=middle border=0>
<INPUT name="face" type=radio class="noborder" value=2>
<img height=20
src="images/face/face2.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=3>
<img height=20
src="images/face/face3.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=4>
<img height=20
src="images/face/face4.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=5>
<img height=20
src="images/face/face5.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=6>
<img height=20
src="images/face/face6.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=7>
<img height=20
src="images/face/face7.gif" width=20 align=middle border=0><br>
<input name="face" type=radio class="noborder" value=8>
<img height=20
src="images/face/face8.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=9>
<img height=20
src="images/face/face9.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=10>
<img height=20
src="images/face/face10.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=11>
<img height=20
src="images/face/face11.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=12>
<img height=20
src="images/face/face12.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=13>
<img height=20
src="images/face/face13.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=14>
<img height=20
src="images/face/face14.gif" width=20 align=middle border=0>
<input name="face" type=radio class="noborder" value=15>
<img height=20
src="images/face/face15.gif" width=20 align=middle border=0><br>
</td>
</tr>
<tr onClick="showCheckCodeClear()">
<td height="38" align="center">Email:</td>
<td colspan="3"><input name="email" type="text" id="email" size="72"></td>
</tr>
<tr onClick="showCheckCodeClear()">
<td height="160" align="center">留言内容:</td>
<td colspan="3">
<textarea name="content" cols="70" rows="10" class="wenbenkuang" id="content">
</textarea>
*</td>
</tr>
<tr>
<td height="42" align="center" valign="bottom" onClick="showCheckCodeClear()">验证码:</td>
<td width="6%">
<div style="position:absolute">
<div id="showCheckCode" style="display:none; padding:3px" align="center" >
<img src="images/checkCodePicture.jpg" id="createCheckCode" width="200" height="60">
<a href="#" style="color:#000000" onClick="getCheckCode1(showCheckCode,checkCode)">看不清?换一个</a>
</div>
<input name="checkCode" type="text" id="checkCode" size="6" value="" title="单击验证码输入框,获取验证码" onClick="getCheckCodeFun(showCheckCode,checkCode);" onBlur="checkCheckCode(this.value)">
</div>
</td>
<td width="6%" valign="bottom" id="resultCheckCode1" onClick="showCheckCodeClear()">
<img id="messageImg" src='images/tishi2.gif' width='16' height='16'>
</td>
<td width="74%" valign="bottom" id="resultCheckCode2" onClick="showCheckCodeClear()">
<div id="resultMessage">温馨提示:单击验证码输入框,获取验证码!验证码区分大小写</div>
</td>
</tr>
<tr onClick="showCheckCodeClear()">
<td height="42" align="center"> </td>
<td colspan="3" >
<input name="btn_Submit" id="btn_Submit" type="button" class="btn_grey" value="保存" onClick="check(form1)" disabled="disabled">
<input name="Submit2" type="reset" class="btn_grey" value="重置">
</td>
</tr>
</table>
</form>
</td>
<td width="6%" onClick="showCheckCodeClear()"> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" class="tableBorder_LR">
<%@include file="copyright.jsp"%>
</td>
</tr>
</table>
<td width="19" background="images/bg_right.gif"> </td>
</tr>
</table>
</body>
</html>
checkCheckCode.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String inCheckCode=request.getParameter("inCheckCode");
if(session.getAttribute("randCheckCode").equals(inCheckCode)){
out.println("1");
}
else{
out.println("0");
}
%>
copyright.jsp
<table width="99%" height="72" border="0" align="center" cellpadding="-2" cellspacing="-2">
<tr>
<td height="2" colspan="4"></td>
</tr>
<tr>
<td width="124" height="23"> </td>
<td valign="bottom" align="center"> CopyRight ?</td>
<td width="141"> </td>
</tr>
<tr>
<td height="28"> </td>
<td align="center"></td>
<td> </td>
</tr>
<tr>
<td height="8"></td>
<td height="8"></td>
<td height="8"></td>
</tr>
</table>
getPictureCheckCode.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.Random" %>
<%Random random=new Random();%>
<img src="<% out.println("PictureCheckCode?rand="+random.nextInt(10000));%>" id="createCheckCode" width="200" height="60">
<a href="#" style="color:#EEEEEE" onclick="getCheckCode1(showCheckCode,checkCode)">看不清?换一个</a>
top.jsp
<table width="761" height="126" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="761" align="left" valign="top">
<img src="images/bg_top.gif" width="761" height="126" />
</td>
</tr>
</table>
style.css
body{
font-size: 9pt;
margin-left:0px;
margin-top:0px;
background-image: url(../images/bg.gif);
scrollbar-face-color: #5ac3f5;
scrollbar-highlight-color: #ffffff;
scrollbar-shadow-color: #fcfcfc; color: #000000;
scrollbar-3dlight-color: #ececec;
scrollbar-arrow-color: #ffffff;
scrollbar-track-color: #ececec;
scrollbar-darkshadow-color: #999966;
background-color: #fcfcfc
}
td {
font-size: 9pt;
line-height:150%;
}
a:hover {
font-size: 9pt;
color: #FF4400;
}
a {
font-size: 9pt;
text-decoration: none;
color: #3C404D;
}
.btn_grey {
font-family: "宋体";
font-size: 9pt;
color: #333333;
background-color: #eeeeee;
cursor: hand;
padding:1px;
height:19px;
border-top: 1px solid #FFFFFF;
border-right:1px solid #666666;
border-bottom: 1px solid #666666;
border-left: 1px solid #FFFFFF;
}
.word_grey {
font-size: 9pt;
color: #333333;
}
.txt_grey {
font-family: "宋体";
font-size: 9pt;
color: #333333;
border: 1px solid #999999;
width:110px;
}
input {
font-family: "宋体";
font-size: 9pt;
color: #333333;
border: 1px solid #999999;
}
.wenbenkuang {
font-family: "宋体";
font-size: 9pt;
color: #333333;
border: 1px solid #999999;
}
.search {
font-family: 宋体;
font-size: 9pt;
color: #000000;
background-color: #EEEEEE;
border: 1px Hidden #000000;
}
.tableBorder {
border: #39B4E2 1px solid
}
.tableBorder_LRB {
border: #39B4E2 1px solid;
border-top-style:none;
}
.tableBorder_LR {
border: #39B4E2 1px solid;
border-top-style:none;
border-bottom-style:none;
}
.tableBorder_Top{
border:1px solid #39B4E2;
border-bottom-style:none;
border-left-style:none;
border-right-style:none
}
.tableBorder_Botton{
border:1px solid #39B4E2;
border-top-style:none;
border-left-style:none;
border-right-style:none
}
hr{
color:#39B4E2;
}
.ToolTip {
border-right: #39b4e2 1px solid;
border-top: #39b4e2 1px solid;
border-left: #39b4e2 1px solid;
color: #333333;
border-bottom: #39b4e2 1px solid;
background-color: #f9f9f9;
}
.noborder{
border-style:none;
}
.tableBorder_B{
border:1px solid #39B4E2;
border-left-style:none;
border-right-style:none;
border-Top-style:none;
}
ajaxRequest.js
let net=new Object();
//编写构造函数
net.AjaxRequest=function(url,onload,onerror,method,params){
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadDate(url,method,params);
}
//编写用于初始化XMLHttpRequest对象并指定处理函数,最后发送HTTP请求的方法
net.AjaxRequest.prototype.loadDate=function(url,method,params){
if (!method){
method="GET";
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
}
else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
let loader=this;
this.req.onreadystatechange=function(){
net.AjaxRequest.onReadyState.call(loader);
}
this.req.open(method,url,true);
if(method=="POST"){
this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
this.req.send(params);
}
catch (err){
this.onerror.call(this);
}
}
}
//重构回调函数
net.AjaxRequest.onReadyState=function(){
let req=this.req;
let ready=req.readyState;
if (ready==4){
if (req.status==200 ){
this.onload.call(this);
}
else{
this.onerror.call(this);
}
}
}
//重构默认的错误处理函籹
net.AjaxRequest.prototype.defaultError=function(){
alert("错误数据\n\n回调状态:"+this.req.readyState+"\n状态: "+this.req.status);
}
check.js
//判断用户的输入是否合法
function check(myform){
if(myform.author.value==""){
alert("留言人不允许为空!");
myform.author.focus();
return;
}
if (myform.email.value!=""){
var i=myform.email.value.indexOf("@");
var j=myform.email.value.indexOf(".");
if((i<0)||(i-j>0)||(j<0)){
alert("您输入的Email地址不正确,请重新输入!");
myform.email.value="";
myform.email.focus();
return;
}
}
if(myform.content.value==""){
alert("留言内容不允许为空!");
myform.content.focus();
return;
}
if(myform.checkCode.value==""){
alert("验证码不允许为空!");
myform.checkCode.focus();
return;
}
alert("留言提交成功!");
myform.submit();
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>verificationCodeDemo2</display-name>
<servlet>
<servlet-name>PictureCheckCode</servlet-name>
<servlet-class>com.demo.PictureCheckCode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PictureCheckCode</servlet-name>
<url-pattern>/PictureCheckCode</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
PictureCheckCode
package com.demo;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class PictureCheckCode extends HttpServlet {
public PictureCheckCode() {
super();
}
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
super.init();
}
public Color getRandColor(int s, int e) {
Random random=new Random();
if (s > 255) s=255;
if (e > 255) e=255;
int r=s + random.nextInt(e - s);
int g=s + random.nextInt(e - s);
int b=s + random.nextInt(e - s);
return new Color(r, g, b);
}
public void service(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=200;
int height=60;
//创建BufferedImage类的对象
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//创建Graphics类的对象
Graphics g=image.getGraphics();
//通过Graphics类的对象创建一个Graphics2D类的对象
Graphics2D g2d=(Graphics2D)g;
//实例化一个Random对象
Random random=new Random();
//通过Font构造字体
Font mFont=new Font("华文宋体", Font.BOLD, 30);
//改变图形的当前颜色为随机生成的颜色
g.setColor(getRandColor(200, 250));
//绘制一个填色矩形
g.fillRect(0, 0, width , height);
//画一条折线
//创建一个供画笔选择线条粗细的对象
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);
//改变线条的粗细
g2d.setStroke(bs);
//设置当前颜色为预定义颜色中的深灰色
g.setColor(Color.DARK_GRAY);
int[] xPoints=new int[3];
int[] yPoints=new int[3];
for(int j=0;j<3;j++){
xPoints[j]=random.nextInt(width - 1);
yPoints[j]=random.nextInt(height - 1);
}
g.drawPolyline(xPoints, yPoints,3);
//生成并输出随机的验证文字
g.setFont(mFont);
String sRand="";
int itmp=0;
for(int i=0;i<4;i++){
if(random.nextInt(2)==1){
//生成A~Z的字母
itmp=random.nextInt(26)+65;
}
else{
//生成0~9的数字
itmp=random.nextInt(10)+48;
}
char ctmp=(char)itmp;
sRand+=String.valueOf(ctmp);
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110));
g.setColor(color);
/****随机缩放文字并将文字旋转指定角度**/
//将文字旋转指定角度
Graphics2D g2d_word=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
trans.rotate(random.nextInt(45)*3.14/180,15*i+10,7);
//缩放文字
float scaleSize=random.nextFloat()+0.8f;
if(scaleSize>1.1f) scaleSize=1f;
trans.scale(scaleSize, scaleSize);
g2d_word.setTransform(trans);
g.drawString(String.valueOf(ctmp),30*i+40,16);
}
//将生成的验证码保存到Session中
HttpSession session=request.getSession(true);
session.setAttribute("randCheckCode",sRand);
g.dispose();
ImageIO.write(image,"JPEG",response.getOutputStream());
}
}
需要servlet和jsp的jar包
工程目录:
ndex.jsp
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" language="java" errorPage="" %>
<html>
<head>
<title>加密的验证码</title>
<link rel="stylesheet" href="css/style.css" />
<script language="javascript">
function myReload(){
//document.createCheckCode.src="PictureCheckCode";
document.getElementById("createCheckCode").src=document.getElementById("createCheckCode").src+"?nocache="+new Date().getTime();
}
</script>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#4F6D92',endColorStr='#ACCBE7',gradientType='0');">
<table width="100%" height="451" border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center"><table width="509" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="142"><img src="images/login_top.jpg" width="509" height="142"></td>
</tr>
<tr>
<td height="159" valign="top" background="images/login_bottom.jpg">
<table width="350" border="0" cellpadding="0" cellspacing="0" background="KCM/login.gif">
<form name="form1" method="post" action="check.jsp" onSubmit="return check();">
<tr>
<td width="84"> </td>
<td width="57" height="28">用户名:</td>
<td colspan="2"><input name="username" type="text" size="29"></td></tr>
<tr>
<td> </td>
<td height="28">密 码:</td>
<td colspan="2"><input name="password" type="password" size="29"></td></tr>
<tr>
<td height="24" align="center"> </td>
<td height="28" align="center">验证码:</td>
<td width="33" height="24" align="left">
<input name="checkCode" title="验证码区分大小写" type="text" size="4" maxlength="4"> </td>
<td width="176" align="left">
<img src="PictureCheckCode" id="createCheckCode" style="border:#999999 solid 1px">
<a href="#" onClick="myReload()">看不清?换一个</a>
</td>
</tr>
<tr>
<td height="37" colspan="4" align="center"><input name="submit" type="submit" class="btn_bg_manageLogin" value="登 录">
<input name="reset" type="reset" class="btn_bg_manageLogin" value="取 消">
</td>
</tr>
</form>
</table></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script language="javascript">
function check(){
if(form1.username.value==""){
alert("请输入用户名!");
form1.username.focus();
return false;
}
if(form1.password.value==""){
alert("请输入密码!");
form1.password.focus();
return false;
}
if(form1.checkCode.value==""){
alert("请输入验证码!");
form1.checkCode.focus();
return false;
}
}
</script>
check.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="encode" class="com.demo.Encode" scope="request"/>
<%
String checkCode=request.getParameter("checkCode").toString();
checkCode=encode.encodeByMD5(checkCode); //进行MD5加密
if("".equals(request.getParameter("username")) || "".equals(request.getParameter("password"))){
out.println("<script>alert('请输入用户名或密码!');window.location.href='index.jsp';</script>");
}
else{
if(!("mr".equals(request.getParameter("username")) && "mrsoft".equals(request.getParameter("password")))){
out.println("<script>alert('您输入的用户名或密码不正确!');window.location.href='index.jsp';</script>");
}
}
if ("".equals(checkCode) || checkCode==null) {
out.println("<script>alert('请输入验证码!');window.location.href='index.jsp';</script>");
}
else {
if (!checkCode.equals(session.getAttribute("randCheckCode"))) {
out.println("<script>alert('您输入的验证码不正确!');window.location.href='index.jsp';</script>");
}
}
%>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="778" height="275" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="115" colspan="2">
<table width="778" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="784" height="115" align="center" valign="top">
<img src="images/logo.jpg" width="778" height="115">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="190"><a href="#" onClick="show_div('menu1')" >
<img src="images/left_top.GIF" width="186" height="33"></a>
<table width="186" height="331" border="0" cellpadding="0" cellspacing="0" class="tableBorder_bold">
<tr>
<td height="323" align="center" valign="top">
<!--基础信息管理-->
<a href="#">
<img name="Imgmenu1" border="0"
src="images/menu_1.JPG" align="ABSMIDDLE" width="165" height="26"></a>
<div id="menu1">
<table width="165" border="0" cellpadding="0" cellspacing="0" class="tableBorder">
<tr><td width="18%" height="24" align="center">
<img src="images/subMenu_ico.GIF" width="4" height="7"></td>
<td width="82%"><a href="#">客户信息管理</a></td>
</tr>
<tr><td height="24" align="center">
<img src="images/subMenu_ico.GIF" width="4" height="7"></td>
<td><a href="#">商品信息管理</a></td>
</tr>
<tr><td height="24" align="center">
<img src="images/subMenu_ico.GIF" width="4" height="7"></td>
<td><a href="#">供应商信息管理</a></td>
</tr>
<tr><td height="24" align="center">
<img src="images/subMenu_ico.GIF" width="4" height="7"></td>
<td><a href="#">商品信息查询</a></td>
</tr>
<tr><td height="24" align="center">
<img src="images/subMenu_ico.GIF" width="4" height="7"></td>
<td><a href="#">客户信息查询</a></td>
</tr>
<tr><td height="24" align="center">
<img src="images/subMenu_ico.GIF" width="4" height="7"></td>
<td><a href="#">供应商信息查询</a></td>
</tr>
</table>
</div>
<!--库存管理-->
<a href="#" >
<img name="Imgmenu3" align="ABSMIDDLE"
src="images/menu_3.JPG" border="0" width="165" height="28"></a><br>
<!--销售管理-->
<a href="#">
<img name="Imgmenu4" align="ABSMIDDLE"
src="images/menu_4.JPG" border="0" width="165" height="28"></a><br>
<a href="#">
<img name="Imgmenu5" align="ABSMIDDLE"
src="images/menu_5.JPG" border="0" width="165" height="28"></a><br>
<a href="#">
<img name="Imgmenu6" align="ABSMIDDLE"
src="images/menu_6.JPG" border="0" width="165" height="28"></a><br>
<a href="index.jsp" >
<img name="Imgmenu7" align="ABSMIDDLE"
src="images/menu_7.JPG" border="0" width="165" height="28"></a><br>
</td>
</tr>
</table></td>
<td width="588"> </td>
</tr>
</table>
</body>
</html>
style.css
td {
font-size: 9pt;
color: #000000;
}
a:hover {
font-size: 9pt;
color: #FF6600;
}
a {
font-size: 9pt;
text-decoration: none;
color: #676767;
noline:expression(this.onfocus=this.blur);
}
img{
border:0;
}
.img1{
border:1px;
}
.blue {
font-size: 9pt;
color: #034683;
}
.bgcolor {
font-size: 9pt;
color: #1980DB;
}
.btn_grey {
font-family:"宋体";
font-size: 9pt;
color: #333333;
background-color: #eeeeee;
cursor: hand;
padding:1px;
height:19px;
border-top: 1px solid #FFFFFF;
border-right:1px solid #666666;
border-bottom: 1px solid #666666;
border-left: 1px solid #FFFFFF;
}
.btn_bg_manageLogin{
background-image:url(../images/login_btn_bg.gif);
border:#436E9B solid 1px;
width:51px;
height:20px;
padding:4px;
color:#000000;
outline-color:#FFFFFF;
}
input{
font-family: "宋体";
font-size: 9pt;
color: #333333;
border: 1px solid #999999;
}
.word_grey{
color:#CFEAFD;
}
.word_deepgrey{
color:#505050;
}
.word_orange{
color:#FF6600;
}
.word_blue{
color:#123F73;
}
.word_white{
color:#FFFFFF;
}
.word_gray{
color:#dddddd;
}
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
.textarea {
font-family: "宋体";
font-size: 9pt;
color: #333333;
border: 1px solid #999999;
}
.tableBorder {
border: #89B7D8 1px solid
}
.hidden_a_line{
noline:expression(this.onfocus=this.blur);
}
.tableBorder_bold {
border: #EEEEEE 4px solid;
padding:5px;
}
.tableBorder_gray {
border: #C7C7C7 1px solid
}
.table1{
background-color:#AEAEAE;
padding:5px;
}
PictureCheckCode.java
package com.demo;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class PictureCheckCode extends HttpServlet {
public PictureCheckCode() {
super();
}
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
super.init();
}
//获取随机颜色
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);
}
public void service(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=70;
int height=17;
BufferedImage image=new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
Graphics2D g2d=(Graphics2D)g;
Random random=new Random();
Font mFont=new Font("华文宋体", Font.BOLD, 17);
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(mFont);
g.setColor(getRandColor(180, 200));
//画随机的线条
for (int i=0; i < 130; i++) {
int x=random.nextInt(width - 1);
int y=random.nextInt(height - 1);
int x1=random.nextInt(6) + 1;
int y1=random.nextInt(12) + 1;
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);
Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
g2d.setStroke(bs);
g2d.draw(line);
}
String sRand="";
//输出随机的验证文字
int itmp=0;
for(int i=0;i<4;i++){
if(random.nextInt(2)==1){
//生成A~Z的字母
itmp=random.nextInt(26)+65;
}
else{
//生成0~9的数字
itmp=random.nextInt(10)+48;
}
char ctmp=(char)itmp;
sRand+=String.valueOf(ctmp);
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110));
g.setColor(color);
/****随机缩放文字并将文字旋转指定角度**/
//将文字旋转指定角度
Graphics2D g2d_word=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
trans.rotate(random.nextInt(45)*3.14/180,15*i+10,6);
//缩放文字
float scaleSize=random.nextFloat()+0.5f;
if(scaleSize<0.8 || scaleSize>1.1f) scaleSize=1f;
trans.scale(scaleSize, scaleSize);
g2d_word.setTransform(trans);
g.drawString(String.valueOf(ctmp),15*i+10,14);
}
//将生成的验证码保存到Session中
HttpSession session=request.getSession(true);
//声明并实例化Encode的实例
Encode encode=new Encode();
//将加密后的验证码保存到Session
session.setAttribute("randCheckCode",encode.encodeByMD5(sRand));
g.dispose();
ImageIO.write(image,"JPEG",response.getOutputStream());
}
}
Encode.java
package com.demo;
import java.security.MessageDigest;
public class Encode {
public String encode(String str, String algorithm) {
if (str==null) {
return null;
}
//声明并实例化StringBuilder类的对象
StringBuilder sb=new StringBuilder();
try {
//创建使用MD5加密算法的对象
MessageDigest code=MessageDigest.getInstance(algorithm);
//将要加密信息中的所有字节提供给该对象
code.update(str.getBytes());
//调用digest方法完成消息摘要的计算,并以字节数组的形式返回消息摘要
byte[] bs=code.digest();
//将加密后的字节数组转换成十六进制的字符串,形成最终的密文
for (int i=0; i < bs.length; i++) {
int v=bs[i] & 0xFF;
if (v < 16) {
sb.append(0);
}
sb.append(Integer.toHexString(v));
}
}
catch (Exception e) {
e.printStackTrace();
}
//将加密后的字符串中的英文字母转换为大写
return sb.toString().toUpperCase();
}
public String encodeByMD5(String str){
return encode(str,"MD5");
}
}
web.xml
网页页面的使用中为防止“非人类”的大量操作和防止一些的信息冗余,增加验证码校验是许多网站常用的方式。
而让用户输入字母和数字组合的验证码是最经典也是最常用的方式。
这一篇是纯利用现有JDK提供的绘图类(ImageIO)类制作,这个过程比较复杂且需要了解ImageIO类。
今天发布的第二篇文章是利用Hutool工具类来实现的,该工具类已经封装验证码所需的相关类等,使用起来较为简单和方便。
验证码的生成和校验过程均使用Servlet和JSP的结合来实现,Servlet的相关内容可以参阅
Servlet技术:https://mp.weixin.qq.com/s/__e_ef0SI6kVPiRaU0MXJw
如何利用基础的JSP知识来实现网页的验证码校验呢?
首先要验证码的校验的过程。
验证码校验分为三部分:
验证码的生成实际就是输出一个图像,所以在这里使用ImageIO来生成图片,然后结合使用随机数(Random)来实现随机生成验证上的内容,最后进而展示出来,然后利用Session对象存储验证码的内容。在用户输入验证码的时候可以用request来获取用户输入的内容,让其余Session对象中保存的验证码内容进行比较,若一致则验证成功,不一致就验证失败。
先创建一个图片的缓冲区:
BufferedImage bi=new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
创建画布:
Graphics g=bi.getGraphics();
创建颜色:
Color c=new Color(200,150,255);
创建背景颜色:
g.setColor(c);
填充矩形:
g.fillRect(0, 0, 68,22);
将要显示的验证码内容组成元素存入字符串数组:
char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
创建随机的验证码内容:
Random r=new Random();
int len=ch.length;
int index; //index用于存放随机数字
StringBuffer sb=new StringBuffer();
for(int i=0;i<4;i++)
{
index=r.nextInt(len);//产生随机数字
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255))); //设置颜色
g.drawString(ch[index]+"",(i*15)+3, 18);//画数字以及数字的位置
sb.append(ch[index]);
}
将验证码的内容存入Session及显示在页面上:
request.getSession().setAttribute("piccode",sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());
完整代码:
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage bi=new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);//创建图像缓冲区
Graphics g=bi.getGraphics(); //通过缓冲区创建一个画布
Color c=new Color(200, 150, 255); //创建颜色
g.setColor(c);//为画布创建背景颜色
g.fillRect(0, 0, 68, 22); //填充矩形
char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//转化为字符型的数组
Random r=new Random();
int len=ch.length;
int index; //index用于存放随机数字
StringBuffer sb=new StringBuffer();
for (int i=0; i < 4; i++) {
index=r.nextInt(len);//产生随机数字
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255))); //设置颜色
g.drawString(ch[index] + "", (i * 15) + 3, 18);//画数字以及数字的位置
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());
}
}
在测试之前需要先在web.xml文件中配置一下:
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.kailong.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/imageServlet</url-pattern>
</servlet-mapping>
启动服务器后在浏览器中输入http://localhost:8080/工程名/imageServlet 即可
验证码的生成已经实现成功,下面实现验证验证码的Servlet。
先新建一个jsp用户界面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/loginServlet" method="get" >
验证码:<input type="text" name="checkCode"/><br/>
<img alt="验证码" id="imagecode" src="<%=request.getContextPath()%>/imageServlet"/>
<input type="submit" value="提交">
</form>
</body>
</html>
校验验证码过程:
代码实现:
获取Session中的验证码内容:
String piccode=(String) request.getSession().getAttribute("piccode");
获取用户输入的验证码内容:
String checkCode=request.getParameter("checkCode");
验证码判断(使用了PrintWriter将相关内容输出)
response.setContentType("text/html;charset=utf-8");//解决乱码问题
PrintWriter out=response.getWriter();
if(checkCode.equals(piccode))
{
out.println("验证码输入正确!");
}
else
{
out.println("验证码输入错误!!!");
}
out.flush();//将流刷新
out.close();//将流关闭
完整代码:
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
//用于验证验证码
{
String piccode=(String) request.getSession().getAttribute("piccode");
String checkCode=request.getParameter("checkCode");
response.setContentType("text/html;charset=utf-8");//解决乱码问题
PrintWriter out=response.getWriter();
if (checkCode.equals(piccode)) {
out.println("验证码输入正确!");
} else {
out.println("验证码输入错误!!!");
}
out.flush();//将流刷新
out.close();//将流关闭
}
}
测试前先在web.xml文件中配置一下:
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.kailong.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
在验证码生成之后,用户在识别的时候可能不能正确识别,这时候就需要刷新一下重新生成。
添加超链接实现刷新:
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
<script>
function reloadCode() {
var time=new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath()%>/imageGenerate?d="+time;
}
</script>
</head>
<body>
<form action="<%=request.getContextPath()%>/loginServlet" method="get" >
验证码:<input type="text" name="checkCode"/><br/>
<img alt="验证码" id="imagecode" src="<%=request.getContextPath()%>/imageServlet"/>
<a href="javascript:reloadCode();">看不清楚</a><br>
<br/><input type="submit" value="提交">
</form>
</body>
</html>
js部分的Date相关是防止浏览器缓存后不能正常刷新,添加时间的唯一性来实现能够及时刷新和展示。
js 部分可以参阅:JavaScript 语言入门: https://mp.weixin.qq.com/s/37CaC25_1agb-aXBLhUKtg
也可以在ImageServlet中添加防止浏览器缓存的语句:
response.setHeader("Pragma", "No-cache");
公众号本文地址:https://mp.weixin.qq.com/s/XHucabQ_WwUx2OMDGSTMkw
欢迎关注公众号:愚生浅末。
*请认真填写需求信息,我们会在24小时内与您取得联系。