jsp页面验证码(完整实例)
项目结构如下,MyEclipse中新建一个Web Project,取名servlet

1、src下new一个servlet类
package com.servlet; import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder; public class IdentityServlet extends HttpServlet { public static final char[] chars={'','','','','','','','','A'};//自定义验证码池
public static Random random=new Random(); //随机数 public static String getRandomString(){ //获取6位随机数,放在图片里
StringBuffer buffer=new StringBuffer();
for(int i=;i<;i++){
buffer.append(chars[random.nextInt(chars.length)]);
}
return buffer.toString();
} public static Color getRandomColor(){ //获取随机的颜色
return new Color(random.nextInt(), random.nextInt(), random.nextInt());
} public static Color getReverseColor(Color c){ //返回某颜色的反色
return new Color( - c.getRed(), - c.getGreen(), - c.getBlue());
} /**
* Constructor of the object.
*/
public IdentityServlet() {
super();
} /**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("image/jpeg"); //设置输出类型 String randomString = getRandomString(); //随机字符串
request.getSession(true).setAttribute("randomString", randomString);//放到session里 int width=; //图片宽度
int height=; //图片高度 Color color=getRandomColor(); //随机颜色,用于背景色
Color reverse=getReverseColor(color);//反色,用于前景色
//创建一个彩色图片
BufferedImage bi=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=bi.createGraphics(); //绘图对象
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,));//设置字体
g.setColor(color);//设置颜色
g.fillRect(, , width, height);//绘制背景
g.setColor(reverse);
g.drawString(randomString, , );//绘制随机字符
for(int i=,n=random.nextInt();i<n;i++){ //画最多100个噪音点
g.drawRect(random.nextInt(width), random.nextInt(height), , );
}
ServletOutputStream out= response.getOutputStream();//转成JPEG格式
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);//编码器
encoder.encode(bi); //对图片进行编码
out.flush(); //输出到客户端
} /**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request, response);
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
2、web.xml,会自动生成servlet和servlet-mapping的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<servlet-name>IdentityServlet</servlet-name>
<servlet-class>com.servlet.IdentityServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>IdentityServlet</servlet-name>
<url-pattern>/servlet/IdentityServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3、WebRoot下新建一个html,展示验证码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function reloadImage(){
document.getElementById('btn').disabled=true;
document.getElementById('identity').src='servlet/IdentityServlet?ts='+new Date().getTime();
}
</script>
</head> <body> <img src="servlet/IdentityServlet" id="identity" onload="btn.disabled=false;" />
<input type=button value="换个图片" onclick="reloadImage()" id="btn">
</body>
</html>
启动Tomcat,输入网址:http://localhost:8080/servlet/identity.html,效果如下:

点击‘换个图片’,会生成新的验证码
jsp页面验证码(完整实例)的更多相关文章
- JSP页面验证码实现
首先在JSP页面加上生成图片的链接 <img type="image" src="auth/authCode" id="codeImage&qu ...
- 微信小程序发送短信验证码完整实例
微信小程序注册完整实例,发送短信验证码,带60秒倒计时功能,无需服务器端.效果图: 代码: index.wxml <!--index.wxml--> <view class=&quo ...
- PHP连接数据库实现多条件查询与分页功能——关于租房页面的完整实例操作
租房页面如图: 代码如下: <!DOCTYPE html><html> <head> <meta charset="UTF-8& ...
- jsp页面简单的验证码实现
前段时间赶着结束毕业设计任务,现在完成了.回来补一下设计毕业设计的过程中遇到的问题和解决方案. 为了使小系统更有模有样,这里尝试在登录页面实现验证码功能.现描述一下我的解决方案. 首先看一下实现后的界 ...
- 利用Div+CSS(嵌套+盒模型)布局页面完整实例流程
Div+CSS(嵌套+盒模型)布局页面完整实例流程: <!DOCTYPE html><html> <head> <meta charset="UT ...
- 解决:jsp 页面不全,response 内容不完整
前言:今天 jsp 页面输出不完整这个问题困扰了我几个小时,终于发现问题并解决了. 环境: tomcat 8.0.17 x64 jsp springmvc vue 问题: 本来页面正常,但加了几行代码 ...
- 超详细的php用户注册页面填写信息完整实例(附源码)
这篇文章主要介绍了一个超详细的php用户注册页面填写信息完整实例,内容包括邮箱自动匹配.密码强度验证以及防止表单重复等,小编特别喜欢这篇文章,推荐给大家. 注册页面是大多数网站必备的页面,所以很有必要 ...
- JSP页面生成验证码功能
<%@ page language="java" contentType="text/html; charset=UTF-8" import=" ...
- JSP页面中验证码的调用方法
步骤: 1.首先是要生成验证码 2.对验证码类进行调用:主要 实现的是 将验证码图片 输出到response.getOutputStream()这个输出流中 调用时,可以在页面调用,也可以在serv ...
随机推荐
- MySQL INSERT插入条件判断:如果不存在则插入
摘要: 我们经常需要进行sql的批量插入,要求:该条记录不存在则插入,存在则不插入.如果使用一条INSERT语句实现呢? 普通的 INSERT INTO 插入: INSERT INTO card(ca ...
- 5.对与表与表之间的关系,efcore是如何处理的
public class Account { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Accoun ...
- 理清C++常量指针和指针常量这团乱麻
写在前面: 与其说C++中的常量指针和指针常量是一块很有嚼头的语法糖,不如说它是一块相当难啃的骨头.其实本来没什么,这无非是const int *p与int* const p的区别, 但一涉及到起名字 ...
- ImageList图标左边有黑色竖线
ImageList图标左边有黑色竖线, 原因 ImageList颜色深度太小引起的,解决方案,把颜色深度调成Depth32Bit 默认: 修改为: 结果: 备注:根据文件获得文件的系统图标: Icon ...
- 监狱3D指纹门禁系统解决方案
由于监狱的行业特殊性,其安全性对社会的安定团结具有重大影响力.因此,采用高新技术来建立监狱的安全屏障,提高监狱安全的规范化.科学化管理水平.用高效的技术防范手段对监狱安全实行事前的主动的防范,保障社会 ...
- 用FileInputStream实现文本复制
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /* * 用f ...
- C++Primer 5th 练习 12.19
这阵子真是太忙了, 连续做了四个课设. 当然这并不能作为好久没写博客的借口, 没写博客的主要原因只有一个: 懒. 最近又开始回顾C++的语法与特性(据说C++就是一门需要反复回顾的语言),以及学习C+ ...
- 如何把 Callback 接口包装成 Promise 接口
最近一段时间一直在看Node.js,在开发过程中经常要调用一些异步接口,通常在接口的最后一个参数会传入一个回调函数,可以用来处理异常,非异常情况.大致模式如下: var fs = require(“f ...
- Mac系统下配置Tomcat
1.下载Tomcat,网址:http://tomcat.apache.org/download-70.cgi: 2.进入终端Terminal,打开配置文件.bash_profile,输入open .b ...
- Java集合常用类特点整理
集合的结构如下图所示: 集合的两个顶级接口分别为:Collection和Map Collection下有两个比较常用的接口分别是List(列表)和Set(集),其中List可以存储重复元素,元素是有序 ...