项目结构如下,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页面验证码(完整实例)的更多相关文章

  1. JSP页面验证码实现

    首先在JSP页面加上生成图片的链接 <img type="image" src="auth/authCode" id="codeImage&qu ...

  2. 微信小程序发送短信验证码完整实例

    微信小程序注册完整实例,发送短信验证码,带60秒倒计时功能,无需服务器端.效果图: 代码: index.wxml <!--index.wxml--> <view class=&quo ...

  3. PHP连接数据库实现多条件查询与分页功能——关于租房页面的完整实例操作

    租房页面如图: 代码如下: <!DOCTYPE html><html>    <head>        <meta charset="UTF-8& ...

  4. jsp页面简单的验证码实现

    前段时间赶着结束毕业设计任务,现在完成了.回来补一下设计毕业设计的过程中遇到的问题和解决方案. 为了使小系统更有模有样,这里尝试在登录页面实现验证码功能.现描述一下我的解决方案. 首先看一下实现后的界 ...

  5. 利用Div+CSS(嵌套+盒模型)布局页面完整实例流程

    Div+CSS(嵌套+盒模型)布局页面完整实例流程: <!DOCTYPE html><html> <head>  <meta charset="UT ...

  6. 解决:jsp 页面不全,response 内容不完整

    前言:今天 jsp 页面输出不完整这个问题困扰了我几个小时,终于发现问题并解决了. 环境: tomcat 8.0.17 x64 jsp springmvc vue 问题: 本来页面正常,但加了几行代码 ...

  7. 超详细的php用户注册页面填写信息完整实例(附源码)

    这篇文章主要介绍了一个超详细的php用户注册页面填写信息完整实例,内容包括邮箱自动匹配.密码强度验证以及防止表单重复等,小编特别喜欢这篇文章,推荐给大家. 注册页面是大多数网站必备的页面,所以很有必要 ...

  8. JSP页面生成验证码功能

    <%@ page language="java" contentType="text/html; charset=UTF-8" import=" ...

  9. JSP页面中验证码的调用方法

    步骤: 1.首先是要生成验证码 2.对验证码类进行调用:主要 实现的是  将验证码图片 输出到response.getOutputStream()这个输出流中 调用时,可以在页面调用,也可以在serv ...

随机推荐

  1. 刘子健的第二次博客——有关CCCCC语言(・᷄ᵌ・᷅)

    刘子健的第二次博客--有关CCCCC语言(・᷄ᵌ・᷅) 下面又到了回答老师问题的时候啦-(・᷄ᵌ・᷅) 有些问题正在深思熟虑中!敬请期待近期的不间断更新! 你有什么技能比大多人(超过90%以上)更好? ...

  2. Java 打印堆栈的几种方法 Exception

    Exception e = new Exception("this is a log"); e.printStackTrace(); //延迟才可以看出效果 Thread.curr ...

  3. yum安装命令的使用方法

    yum安装常用软件的命令 #yum check-update #yum remove 软件包名 #yum install 软件包名 #yum update 软件包名 yum命令常见使用方法 yum - ...

  4. C#解决一个奇怪的,命名空间“XXX”中不存在类型或命名空间名称“xxx”的问题

    最近做项目时,引用了一个第三方的程序集,代码层面没有任何语法错误,编译提示:命名空间"System.Net"中不存在类型或命名空间名称"FtpClient".是 ...

  5. CentOS搭建NodeJS环境

    事件驱动,承受高并发……这些耀眼的光环,使前端开发者不能不去学习NodeJS. 今天就在开发环境把NodeJS搭建起来了. 1. 下载node wget http://nodejs.org/dist/ ...

  6. JS中函数声明与函数表达式的不同

    Js中的函数声明是指下面的形式: function functionName(){   } 这样的方式来声明一个函数,而函数表达式则是类似表达式那样来声明一个函数,如 var functionName ...

  7. Ubuntu 16.04安装搜狗输入法

    转载: http://www.it610.com/article/5319575.htm 打开firefox浏览器,输入网址www.baidu.com,打开后搜索搜狗拼音 linux进入到搜狗拼音li ...

  8. 平衡二叉树AVL

    1.定义 平衡二叉树(Balanced Binary Tree)是二叉查找树的一个改进,也是第一个引入平衡概念的二叉树.1962年,G.M. Adelson-Velsky 和 E.M. Landis发 ...

  9. js流程控制题——如何实现一个LazyMan

    先说一下想要的效果: lazyMan('zz').eat('lunch').sleep('3').eat('dinner')输出: Hi!This is zz! Eat lunch~ //有3s间隔等 ...

  10. java aes_cbc_256 加密解密

    在之前我们在openssl上和ios上分别测试了 AES256位cbc模式的加密和解密 今天用java提供的api来测试一下:进而确定一下在PC,iOS,安卓上三个平台下的加密解密数据: 1. 首先通 ...