java web 实现验证码
验证码的作用:通常的登录或者注册系统时,都会要求用户输入验证码,以此区别用户行为和计算机程序行为,目的是有人防止恶意注册、暴力破解密码等。
实现验证码的思路:用 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>
     <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.项目结构、效果截图:
java web 实现验证码的更多相关文章
- Java Web模块——验证码模块
一.什么是验证码及它的作用 验 证码为全自动区分计算机和人类的图灵测试的缩写,是一种区分用户是计算机的公共全自动程序,这个问题可以由计算机生成并评判,但是必须只有人类才能解答. 可以防止恶意破解密码. ...
- java web中验证码生成的demo
首先创建一个CaptailCode类 package com.xiaoqiang.code; import java.awt.*; import java.awt.font.FontRenderCon ...
- Java Web之验证码
今天来模拟一下验证码,我们需要三个文件,两个Servlet,一个jsp 直接贴代码吧 RandomCodeServlet:主要负责生产验证码 package com.vae.RandomCode; i ...
- Java web 学习之旅
java web学习之旅 来公司十天了,感觉已经慢慢地融入了这个环境中,几个学长人都很好,都是在他们帮助下,我才能比较顺利的开始了学习java web的旅途. 来这里学习的第一个阶段是做一个简单的用户 ...
- java web实现 忘记密码(找回密码)功能及代码
java web实现 忘记密码(找回密码)功能及代码 (一).总体思路 (二).部分截图 (三).部分代码 (一).总体思路: 1.在 找回密码页面 录入 姓名.邮箱和验证码,录入后点击[提交]按钮, ...
- Java Web整合开发(3) -- Servlet
Servlert基本程序架构: (FirstServlet.java + web.xml) FirstServlet.java package com.helloben.servlet; import ...
- Java web项目综合练习(Estore)
Java web项目综合练习(Estore) 复习day18: ajax代码的书写步骤 2)json格式文本,转js对象的方法是那个 项目开发流程介绍 这里学习的JavaWEB项目实战,主要是把前面学 ...
- java web 整合开发王者归来学习总结
第一章java web开发概述 胖客户端CS,瘦客户端BS(Browser) 网址请求---服务器处理响应-----返回结果-----浏览器显示 CGI可以动态生成页面,但是每个进程都要启动一个CGI ...
- Java Web(三) 会话机制,Cookie和Session详解(转载)
https://www.cnblogs.com/whgk/p/6422391.html 很大一部分应该知道什么是会话机制,也能说的出几句,我也大概了解一点,但是学了之后几天不用,立马忘的一干二净,原因 ...
随机推荐
- window.onload与$.ready的差别
在做图书管理系统的时候.实用到window.onload(){}方法.可是遇到了一个问题.就是怎么都不运行,究竟是为什么呢?愁了半天.后来经师姐指点改用了$.ready(){}. 在我的浅浅的了解中觉 ...
- KMP算法具体解释(转)
作者:July. 出处:http://blog.csdn.net/v_JULY_v/. 引记 此前一天,一位MS的朋友邀我一起去与他讨论高速排序,红黑树,字典树,B树.后缀树,包含KMP算法,只有在解 ...
- lucene和egg项目的异同点
1 和lucene一样 支持全域索引 2 对字符串域提供全文检索,对数字类型域提供范围查询 3 采取和lucene类似的倒排表压缩方式 4 和lucene的多级跳转表不同,egg采取的是B+树做索引, ...
- NDK debug模式
NDK默认是使用NDEBUG宏的,assert也默认不生效,若要开启assert,按以下步骤: 1.編譯NDK代碼時,後面加上NDK_DEBUG=1 ,如: ndk-build NDK_BUILD=1 ...
- [原创]-CMD命令设置IP地址
问题描述 在实际工作中,尤其是像我们这种BI分析人员,在做项目的时候,时常都需要因客户的不同随时切换不同的网络环境,有时可能需要在公司和客户之间来回的穿梭.交替.问题也就随之而来:每次客户那里都需要设 ...
- Android实现XML解析技术
转载:Android实现XML解析技术 本文介绍在Android平台中实现对XML的三种解析方式. XML在各种开发中都广泛应用,Android也不例外.作为承载数据的一个重要角色,如何读写XML成为 ...
- 二手奢侈品电商Vestiaire Collective融资2000万美元
巴黎奢侈品电商Vestiaire Collective获得了2000万美元的C轮融资,投资方包括知名出版集团Condé Nast.Idinvest.Balderton和Ventech,其中Condé ...
- iOS tabbar 控制器基本使用
RootViewController *rootVC=[[RootViewController alloc] init] SignInViewController *signVC = [[SignIn ...
- 控制反转(IoC)
大量使用工厂模式引起的问题: Client 对象需要使用 Service1 的 execute( ) 方法完成特定功能,而 Service1 的实现 Service1Impe类 ...
- 【LeetCode 1】算法修炼 --- Two Sum
Question: Given an array of integers, find two numbers such that they add up to a specific target nu ...