使用servlet实现验证码--IMooC笔记

2024-01-15 00:32

本文主要是介绍使用servlet实现验证码--IMooC笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需要用到验证码时,调用生成验证码图片的servlet即可

生成图片

1.BufferedImage图像数据缓冲区

2.Graphics绘制图片

3.通过Random产生随机验证码信息

4.使用Graphics绘制图片

5.记录验证码信息到session中

6.使用ImageIO输出图片


校验验证码是否正确

1.获取页面验证码

2.获取session保存的验证码

3.比较验证码

4.返回校验结果

两个servlet一个是生成验证码的ImageServlet,另一个是校验验证码的LoginServlet

<?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>ImageServlet</servlet-name><servlet-class>com.nicolashe.ImageServlet</servlet-class></servlet><servlet-mapping><servlet-name> ImageServlet</servlet-name><url-pattern>/servlet/ImageServlet</url-pattern></servlet-mapping><servlet><servlet-name>LoginServlet</servlet-name><servlet-class>com.nicolashe.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name> LoginServlet</servlet-name><url-pattern>/servlet/LoginServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>

生成验证码ImageServlet.java

package com.nicolashe;import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class ImageServlet extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse response){BufferedImage bi=new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);Graphics g=bi.getGraphics();Color c=new Color(200,150,255);g.setColor(c);g.fillRect(0, 0, 68, 22);//上面画了一个框/* *********************** */char[] ch="ABCDEFGHIJKLMNOPQRSTUVWXYZ01234546789".toCharArray();Random r=new Random();int len=ch.length;int index;StringBuffer sb=new StringBuffer();for(int i=0;i<4;i++){index=r.nextInt(len);g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));g.drawString(ch[index]+"", (i*15)+3,18);sb.append(ch[index]);}request.getSession().setAttribute("piccode", sb.toString());try {ImageIO.write(bi, "JPG", response.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

校验验证码的LoginServlet.java:

package com.nicolashe;import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response){String piccode=(String)request.getSession().getAttribute("piccode");String checkcode=request.getParameter("checkcode");response.setContentType("text/html;charset=utf-8");checkcode=checkcode.toUpperCase();try {PrintWriter out=response.getWriter();if(checkcode.equals(piccode)){out.println("验证码正确");}else{out.println("验证码错误");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

验证码输入页面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>My JSP 'index.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">--><script type="text/javascript">function reloadCode(){//备注是的代码不会使页面刷新,因为页面有缓存//document.getElementById("imagecode").src="<%=request.getContextPath()%>/servlet/ImageServlet"//给页面传递一个参数,时间参数,时间时刻在变化,所以每一次点击刷新都被浏览器认为是一次新的请求var time=new Date().getTime();document.getElementById("imagecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+time;}</script></head><body><form action="<%=request.getContextPath()%>/servlet/LoginServlet" method="get">验证码:<input type="text" name="checkcode" /><img alt="验证码"  id="imagecode" src="<%=request.getContextPath()%>/servlet/ImageServlet"/><a href="javascript:reloadCode()">看不清</a><br><input type="submit" value="提交"></form></body>
</html>





这篇关于使用servlet实现验证码--IMooC笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/607041

相关文章

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期