在Servlet中,设置响应正文的类型为image/jpeg,表示响应的是一个图片,然后通过java.awt包中的操作图形图像的类来生成一个图像

  • java.awt.image.BufferedImage:创建该对象时,会在缓存中构造一个图像

  • java.awt.Graphics:该类的对象表示一个画笔,用来话矩形,写字,添加颜色

  • java.util.Random:该类的对象用于生成随机输

    新建ValidateCodeServlet类

    public class ValidateCodeServlet extends HttpServlet {

     /*** Constructor of the object.*/public ValidateCodeServlet() {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 {this.doPost(request, response);}/*** 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  Color getRandomColor(int fc,int bc){Random random = new Random();Color randomColor = null;if(fc>255) fc=255;if(bc>255) bc=255;//设置个0-255之间的随机颜色值int r=fc+random.nextInt(bc-fc);int g=fc+random.nextInt(bc-fc);int b=fc+random.nextInt(bc-fc);randomColor = new Color(r,g,b);return randomColor;//返回具有指定红色、绿色和蓝色值的不透明的 sRGB 颜色}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//禁止页面缓存response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "No-cache");response.setDateHeader("Expires", 0);response.setContentType("image/jpeg");      //设置响应正文的MIME类型为图片int width=60, height=20;  /**创建一个位于缓存中的图像,宽度60,高度20 */  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);      Graphics g = image.getGraphics();              //获取用于处理图形上下文的对象,相当于画笔Random random = new Random();             //创建生成随机数的对象g.setColor(getRandomColor(200,250));        //设置图像的背景色g.fillRect(0, 0, width, height);            //画一个矩形   ,坐标(0,0),宽度60,高度20 g.setFont(new Font("Times New Roman",Font.PLAIN,18));    //设定字体格式g.setColor(getRandomColor(160,200));for(int i=0;i<130;i++){                     //产生130条随机干扰线int x = random.nextInt(width);   int y = random.nextInt(height);   int xl = random.nextInt(12);   int yl = random.nextInt(12);   g.drawLine(x,y,x+xl,y+yl);            //在图象的坐标(x,y)和坐标(x+x1,y+y1)之间画干扰线 } String strCode="";  for (int i=0;i<4;i++){   String strNumber=String.valueOf(random.nextInt(10)); //把随机数转换成String字符串strCode=strCode+strNumber;//设置字体的颜色g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));g.drawString(strNumber,13*i+6,16);       //将验证码依次画到图像上,坐标(x=13*i+6,y=16)}request.getSession().setAttribute("Code",strCode);         //把验证码保存到Session中   g.dispose();  //释放此图像的上下文以及它使用的所有系统资源ImageIO.write(image, "JPEG", response.getOutputStream());    //输出JPEG格式的图像    response.getOutputStream().flush();                        //刷新输出流 response.getOutputStream().close();                         //关闭输出流 }/*** Initialization of the servlet. <br>** @throws ServletException if an error occurs*/public void init() throws ServletException {// Put your code here}
    

    }

index.jsp页面

<%@ 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>用户注册</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">--><style type="text/css">table{font-size:12px;font-family: 隶书;color:gray;border: 1px green solid;}input{font-size:12px;font-family: 隶书;color:gray;}</style></head><body><form action="" method="post"><table align="center"><tr><td>用户名:</td><td><input type="text" name="name" /></td></tr><tr><td>密码:</td><td><input type="password" name="pwd" /></td></tr><tr><td>性别:</td><td><input type="radio" name="sex" value="男" />男<input type="radio" name="sex" value="女" />女</td></tr><tr><td>年龄:</td><td><input type="text" name="age" /></td></tr><tr><td>Email:</td><td><input type="text" name="email" /></td></tr><tr><td>验证码:</td><td><img alt="" src="validatecode" ></td></tr><tr><td>输入验证码:</td><td><input type="text" name="code"/></td></tr><tr><td colspan="2" align="center"><input type="submit" value="注 册" /><input type="reset" value="重 置" /></td></tr></table></form></body>
</html>

web.xml文件配置

<servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>ValidateCodeServlet</servlet-name><servlet-class>com.lh.servlet.ValidateCodeServlet</servlet-class></servlet><servlet-mapping><servlet-name>ValidateCodeServlet</servlet-name><url-pattern>/validatecode</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>

利用Servlet生成动态验证码相关推荐

  1. Servlet生成动态验证码

    主要代码 public class Abc extends HttpServlet { private static final long serialVersionUID = 1L; public ...

  2. 登陆界面如何生成动态验证码

    在设计登录界面时验证码是必不可少,本实例将简单的生成动态验证码. 根据个人需求将生成验证码代码放到不同的的地方,可以放到前段控制器中通过请求方式生成验证码,也可已将代码放到一个JSP页面通过应用JSP ...

  3. phpgif图片包_php生成动态验证码gif图片

    这是一个通过php生成的动态验证码图片的示例,重点是可以运行哦!下面先发下效果图: 下面是php生成动态验证码需要用到的相关类和函数. /** *ImageCode 生成包含验证码的GIF图片的函数 ...

  4. .NET中生成动态验证码

    NET中生成动态验证码 验证码是图片上写上几个字,然后对这几个字做特殊处理,如扭曲.旋转.修改文字位置,然后加入一些线条,或加入一些特殊效果,使这些在人类能正常识别的同时,机器却很难识别出来,以达到防 ...

  5. 利用 PIL模块实现生成动态验证码

    简单说下需求: 当用户点击动态框时,实现实时更换动态库里的数字更换 模块: PIL  io 前端页面: <img src="/get_code/" alt="&qu ...

  6. 生成动态验证码的jsp

    直接将验证码的生成工作放到jsp中,就可以直接在页面请求这个jsp,不需要再去设置servlet的的映射路径,简化代码. <%@ page language="java" p ...

  7. servlet生成网站验证码

    Servlet 最近在学习Servlet,以我的理解:servlet就是运行在服务器端的一个程序,在需要时(如客户端输入某个url时),web容器自动调用某个servlet实现某个功能.我用Servl ...

  8. java生成动态验证码_动态生成验证码案例

    servlet代码 package cn.guizimo.web.servlet; import javax.imageio.ImageIO; import javax.servlet.Servlet ...

  9. java生成动态验证码_java动态生成验证码

    后台代码:RandomImageServlet.java package com.zhaoran.servlet; import java.awt.Color; import java.awt.Fon ...

最新文章

  1. Python编程规范及性能优化
  2. linux分区大容量加入lvm,linux 添加磁盘+lvm扩容
  3. 2springboot:快速创建springboot项目
  4. 学成在线--5.CMS页面管理开发(修改页面)
  5. android webview调js方法,Android中WebView与H5的交互,Native与JS方法互调
  6. 算法分析-动态规划-01背包
  7. 计算hashCode的常见方法
  8. 大平房到朝阳环路时间表_冰蓄冷系统设计计算10大要点
  9. linux 误删文件夹恢复工具,恢复Linux误删除文件系列之foremost工具
  10. logistic回归分析优点_糖尿病前期患者焦虑现状调查及影响因素分析
  11. 过7游戏c语言,C语言实现扫雷小游戏
  12. QQ聊天记录多角度分析Python实现
  13. Java简易转码工具(一个字符串编码是GBK的文本文件,内容转成UTF-8编码)
  14. 不可能得到的最短骰子序列
  15. GMAC接口(1)——GMAC简介
  16. 《用 Python 学微积分》笔记 3
  17. 加拿大综合类大学排名获关注,盘点高校对雅思要求
  18. 读内存为什么比读取磁盘快?快多少?
  19. 关于【天池精准医疗大赛——人工智能辅助糖尿病遗传风险预测】的思考
  20. 线程函数参数(LPVOID Param)

热门文章

  1. MongoDB数据库--扩展Base64,算法
  2. 跳出小程序 video组件 卡顿、黑屏、全屏等坑
  3. 将js进行到底:node学习10
  4. 通过构造函数来创建新对象
  5. C++源码的调用图生成
  6. Linux Kernel系列一:开篇和Kernel启动概要
  7. JSTL笔记—c标签
  8. 把JavaScript代码写在css里
  9. Day03-卷积神经网络原理与使用
  10. linux 7 zip软件下载,linux安装使用7zip教程