验证码的作用:通常的登录或者注册系统时,都会要求用户输入验证码,以此区别用户行为和计算机程序行为,目的是有人防止恶意注册、暴力破解密码等。

实现验证码的思路:用 server 实现随机生成数字和字母组成图片的功能,用 jsp 页面实现显示验证码和用户输入验证码的功能,再用 server 类分别获取图片和用户输入的数据,判断两个数据是否一致。

代码实现

1.编写数字、英文随机生成的 server 类,源码:

 package com;

 import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter; import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class logcheck extends HttpServlet { public logcheck() {
super();
} public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request, response);
} /*实现的核心代码*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("image/jpeg");
HttpSession session=request.getSession();
int width=60;
int height=20; //设置浏览器不要缓存此图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0); //创建内存图像并获得图形上下文
BufferedImage image=new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics(); /*
* 产生随机验证码
* 定义验证码的字符表
*/
String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rands=new char[4];
for(int i=0;i<4;i++){
int rand=(int) (Math.random() *36);
rands[i]=chars.charAt(rand);
} /*
* 产生图像
* 画背景
*/
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height); /*
* 随机产生120个干扰点
*/ for(int i=0;i<120;i++){
int x=(int)(Math.random()*width);
int y=(int)(Math.random()*height);
int red=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
g.setColor(new Color(red,green,blue));
g.drawOval(x, y, 1, 0);
}
g.setColor(Color.BLACK);
g.setFont(new Font(null, Font.ITALIC|Font.BOLD,18)); //在不同高度输出验证码的不同字符
g.drawString(""+rands[0], 1, 17);
g.drawString(""+rands[1], 16, 15);
g.drawString(""+rands[2], 31, 18);
g.drawString(""+rands[3], 46, 16);
g.dispose(); //将图像传到客户端
ServletOutputStream sos=response.getOutputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", baos);
byte[] buffer=baos.toByteArray();
response.setContentLength(buffer.length);
sos.write(buffer);
baos.close();
sos.close(); session.setAttribute("checkcode", new String(rands));
} public void init() throws ServletException {
// Put your code here
} }

2.用于显示验证码的页面:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>index</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<form action="yanzheng" method="post">
<input type="text" name="name" size="5" maxlength="4">
<a href="index.jsp"><img border="0" src="logcheck"></a><br><br>
&nbsp&nbsp&nbsp&nbsp&nbsp<input type="submit" value="提交">
</form>
</body>
</html>

3.用于检验输入的验证码是否正确:

 package com;

 import java.io.IOException;
import java.io.PrintWriter; import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class yanzheng extends HttpServlet { public yanzheng() {
super();
} public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request, response);
}
/*核心代码*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String info=null;
/*获取输入的值*/
String value1=request.getParameter("name"); /*获取图片的值*/
HttpSession session=request.getSession();
String value2=(String)session.getAttribute("checkcode"); /*对比两个值(字母不区分大小写)*/
if(value2.equalsIgnoreCase(value1)){
info="验证码输入正确";
}else{
info="验证码输入错误";
}
System.out.println(info);
request.setAttribute("info", info);
request.getRequestDispatcher("/login.jsp").forward(request, response);
} public void init() throws ServletException {
// Put your code here
} }

4.显示输入结构界面(输入验证码是否正确):

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<%=request.getAttribute("info") %>
</body>
</html>

5.项目结构、效果截图:

最新文章

  1. Lua 安全调用 metatable 的简单应用
  2. Java 枚举用法详解
  3. sublime快捷键整理
  4. Java 实现二分法查找算法
  5. Linux内核态用户态相关知识
  6. Junit手动/自动加载spring配置文件
  7. Hadoop集群错误
  8. 显示scrollbar
  9. poi实现Excel导出
  10. .NET面试题解答
  11. picturefill + picture 标签 实现兼容性很棒的 响应式图片 自适应 屏幕大小
  12. Oracle SQL 语言分类
  13. 51nod_1253:Kundu and Tree(组合数学)
  14. angular 4 实现的tab栏切换
  15. Python 爬虫练习(三) 利用百度进行子域名收集
  16. asp.net core如何自定义端口/修改默认端口
  17. Redis进阶实践之十四 Redis-cli命令行工具使用详解第一部分
  18. python3 输出系统信息
  19. Ajax与CORS通信
  20. 公网定制化yum仓库部署

热门文章

  1. [Angular 2] Set Properties on Dynamically Created Angular 2 Components
  2. php-cli模式学习(PHP命令行模式)(转)
  3. epoll的使用
  4. 疑难杂症:java.lang.AbstractMethodError: org.apache.xerces.dom.DocumentImpl.setXmlVersion(Ljava/lang/String;)V
  5. 实例源码--IOS高仿微信打飞机游戏(完整功能)
  6. Mybatis-Generator 自动生成Dao、Model、Mapping相关文档
  7. 1.4.2 solr字段类型--(1.4.2.1)字段类型定义和字段类型属性
  8. 关键字提取算法之TF-IDF扫盲
  9. 【阿里云产品公测】开放搜索服务 opensearch java jdk 应用体验之 机器人聊天
  10. 要检测两个C文件的代码的抄袭情况