验证码不用多说,在 WEB-APP 中一般应用于:登录、注册、买某票、秒杀等场景。大家都接触过~可以说是千奇百怪,各式各样。
DEMO 目标功能
开工
页面:demo1.jsp
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<%@ 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>
|
说明:
"看不清?换一张" 的 href 属性写成 javascript:void(0) 是为了防止页面刷新,这里的更换功能交给 AJAX 异步完成。
JavaScript 工具:util.js(为啥用原生 JS?任性呗~哈)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/**
* 获取 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;
}
|
页面中的 JavaScript 代码
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<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>
|
生成验证码的 CaptchaCodeServlet.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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);
}
}
|
说明:
这里使用了 Servlet3.0 的新特性-用注解配置 url-pattern(用起来挺爽的),也就是说简单的项目不再需要 web.xml 了,但是 Tomcat 需要 7.0+。
其次生成验证码我用了一个小工具:ValidateCode.jar。工具十分简单,不合心意完全可以自己写。但也就是因为功能太少,所以我又写了一个 ImageUtil。我也有打算自己开源一个验证码工具出来。
ImageUtil.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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() {} // 工具类私有化构造方法是常见的做法
}
|
说明:
为什么要把图片二进制数据进行 Base64编码 呢?因为<img/>标签虽然可以直接设置 src 属性值为${pageContext.request.contextPath}/captcha/code请求相应的 Servlet 来得到二进制数据直接显示,但在 AJAX 异步请求中响应返回的是 xhr.responseText 。当把数据直接给 img 标签的 src 属性时,用 Chrome-tool 查看只会是一堆二进制当作文本解析的乱码字符,所以才要多这一步。
或许我作为萌新不知道一些其它的方便技巧。但若不想使用异步,那直接 img src 设置为请求地址将是最简单的选择,更换验证码无非是监听事件 img src 重新设置为该地址(再来一次请求)。
后台验证验证码:CheckServlet.jave
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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);
}
}
|
说明:
doGet() 方法一开始是对中文乱码进行处理,编码统一设为 UTF-8。在实际项目中,编码问题通常交给一个 Filter 完成,达到一劳永逸的效果。
效果
警告!警告!!颜控请速速撤离!!!
写在最后
以上就是 JavaWeb 验证码小 DEMO 的全部内容啦,最好是把验证提交也搞成异步的,这里就不整了。WEB 项目中还没尝试过添加验证码功能的小伙伴可以动手搞起来啦!实际项目中利用 JQuery 等框架处理 AJAX,再配上一个漂亮的前端页面就完美啦。
以上所述是小编给大家介绍的JavaWeb 实现验证码功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
原文链接:http://www.jianshu.com/p/9284a31e6ce8
相关文章
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-25 35
-
2025-05-25 24
-
2025-05-29 83
-
2025-05-29 88
-
2025-05-29 76


