<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>验证示例</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<style type="text/css">
img {
width: 87px;
height: 33px;
border: 1px solid gray;
}
#msg {color: red;} /* 后台返回的验证信息显示为红色 */
</style>
</head>
<body>
<form action="${pageContext.request.contextPath}/check" method="post" enctype="application/x-www-form-urlencoded">
验证码:<input type="text" name="code" size="4" maxlength="4" id="code" />
<img id="code-img" src="" alt="验证码" style="display: none;"/>
<a href="javascript:void(0)" rel="external nofollow" id="changeCode">看不清?换一张</a> <br/><br/>
<input type="submit" value="验证"/> <span id="msg">${msg}</span>
</form>
</body>
</html>
/**
* 获取 XMLHttpRequest Object
* @returns XMLHttpRequest Object
*/
function getXHR() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) { // Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Sorry, 您的浏览器不支持 AJAX!");
return false;
}
}
}
return xmlHttp;
}
<script type="text/javascript" src="${pageContext.request.contextPath}/js/util.js"></script>
<script type="text/javascript">
var xhr = getXHR(); // 获得 XMLHttpRequest 对象
// 页面加载时加载验证码,但验证码初始为隐藏状态
window.onload=function() {
// 为 onreadystatechange 事件注册回调函数。由于 xhr 为全局变量,所以注册后就不用管啦
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && xhr.status==200) {
document.getElementById('code-img').src="data:image/png;base64,"+xhr.responseText;
}
}
xhr.open("GET","${pageContext.request.contextPath}/captcha/code",true);
xhr.send(null);
}
// 验证码输入框获得焦点时,验证码状态更改为显示
document.getElementById('code').onfocus=function() {
document.getElementById('code-img').style.display="inline";
}
// 异步请求,更换验证码
document.getElementById('changeCode').onclick=function() {
xhr.open("GET","${pageContext.request.contextPath}/captcha/code",true);
xhr.send(null);
}
</script>
package com.leo.web.captcha;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.leo.util.ImageUtil;
import cn.dsna.util.images.ValidateCode;
@WebServlet("/captcha/code")
public class CaptchaCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// 生成验证码(构造参数分别代表:宽度,高度,字符数,干扰线条数)
ValidateCode code = new ValidateCode(87, 33, 4, 23);
// 将验证码保存到 session 中,用于验证
request.getSession().setAttribute("code", code.getCode());
// 响应返回验证码图片 base64 编码后的数据给浏览器
response.getWriter().write(ImageUtil.encodeImg2Base64(code.getBuffImg(), "png"));
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doGet(request, response);
}
}
package com.leo.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import sun.misc.BASE64Encoder;
public class ImageUtil {
/**
* 将图片二进制数据进行 base64 编码
* @param bufImg
* @return base64 编码后的字符串
*/
public static String encodeImg2Base64(BufferedImage bufImg, String formatName) {
ByteArrayOutputStream outputStream = null;
try {
outputStream = new ByteArrayOutputStream();
ImageIO.write(bufImg, formatName, outputStream);
} catch (IOException e) {
throw new RuntimeException("Base64 编码失败!"+e.getMessage());
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outputStream.toByteArray());
}
private ImageUtil() {} // 工具类私有化构造方法是常见的做法
}
package com.leo.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/check")
public class CheckServlet extends HttpServlet {
private static final long serialVersionUID = -6588625852621588221L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String encoding = "UTF-8";
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
/* 验证码验证 */
String inputCode = request.getParameter("code");
// 获得 session 中的正确验证码
String realCode = (String) request.getSession().getAttribute("code");
System.out.println("input: "+inputCode+"\nreal: "+realCode); // 用于 Debug
if(!(inputCode!=null && realCode!=null &&
inputCode.equalsIgnoreCase(realCode))) {
// 若验证码不正确:回到页面并提示错误
request.setAttribute("msg", "验证码错误!请重新输入");
request.getRequestDispatcher("/demo1.jsp").forward(request, response);
return;
}
// 验证码正确,响应一句话表示 OK
response.getWriter().write("验证成功!");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有