在java后台中生成验证码的ImageIO传到前端页面显示,同时把验证码的value值传入session 中用于与用户输入的验证码进行匹配,在用户验证中使用ajax技术,在不刷新页面的同时进行验证码验证。
程序结构图:
VerifyCodeUtils程序主要内容为通过java生成验证码的图片,以及验证码的value值,程序如下:
package utils; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Random; public class VerifyCodeUtils { private static BufferedImage image = null; private static Random random = new Random(); //在自己定义的一些数中,生成4位随机数 public static String getVerifyCode() { String str = ""; char[] code = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U', 'V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t', 'u','v','w','x','y','z','2','3','4','5','6','7','8','9'}; Random random = new Random(); for(int i = 0; i < 4; i++) { str += String.valueOf(code[random.nextInt(code.length)]); } return str; } //生成验证码图像 public static Map getVerifyCode(int width, int heigth) { VerifyCodeUtils.image = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) VerifyCodeUtils.image.getGraphics(); String verifyCode = getVerifyCode(); Map map = new HashMap(); map.put("verifyCode", verifyCode); //将图像填充为白色 g.setColor(Color.WHITE); g.fillRect(0, 0, width, heigth); //设置字体 g.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, heigth-10)); //画边框。 g.setColor(VerifyCodeUtils.getColor()); g.drawRect(0, 0, width, heigth); //随机产生干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(Color.BLACK); for (int i = 0; i < 50; i++) { int x = VerifyCodeUtils.random.nextInt(width); int y = VerifyCodeUtils.random.nextInt(heigth); int xl = VerifyCodeUtils.random.nextInt(5); int yl = VerifyCodeUtils.random.nextInt(5); g.setColor(getColor()); g.drawLine(x, y, x + xl, y + yl); } char c; for(int i = 0; i < 4; i++) { c = verifyCode.charAt(i); g.drawString(c+"", i*20+40, heigth-10); } map.put("image", VerifyCodeUtils.image); return map; } //随机化颜色 public static Color getColor() { int red = 0, green = 0, blue = 0; // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。 red = VerifyCodeUtils.random.nextInt(255); green = VerifyCodeUtils.random.nextInt(255); blue = VerifyCodeUtils.random.nextInt(255); return new Color(red,green,blue); } }
VerifyCodeServlet把VerifyCodeUtils生成的验证码图片通过io流传入前端显示,代码如下:
package Servlet; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import utils.VerifyCodeUtils; /** * Servlet implementation class VerifyCodeServlet */ @WebServlet("/") public class VerifyCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public VerifyCodeServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Expires", "-1"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-type", "image/jpeg"); Map map = VerifyCodeUtils.getVerifyCode(223, 50); //把verifyCode的数值传入session中用于验证用户输入的验证码是否正确 request.getSession().setAttribute("verifyCode", map.get("verifyCode").toString().toUpperCase()); //通过IO流传入前端显示 ImageIO.write((BufferedImage) map.get("image"), "jpg", response.getOutputStream()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
页面jsp代码如下:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!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"> <base id="base" href="${pageContext.request.contextPath}"> <title>验证码测试界面</title> <style> div{float:left;} input{width:223px;height:31px;margin-right:20px;} img{width:223px;height:35px;} p{margin:10px;} </style> </head> <body> <script src="/UploadFiles/2021-04-02/demo.js">js 实现ajax代码如下:
/** * */ function check_verifyCode(){ var XMLHttpReqVerifyCode = null; var url =document.getElementById("base").href +"/servlet/TestVerifyCodeServlet"; var verifyCode = document.getElementById("verifyCode").value; var tip = document.getElementById("tip"); var errorTip = "输入的验证码不正确"; var successTip = "输入的验证码正确"; tip.innerHTML=errorTip; if(verifyCode==null || verifyCode==""){ tip.innerHTML=errorTip; tip.style.color = "red"; }else{ if(window.XMLHttpRequest) { //DOM2浏览器 XMLHttpReqVerifyCode = new XMLHttpRequest(); } else if(window.ActiveXObject) { //使用json语法创建数组 var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP']; for(var i = 0; i < MSXML.length; i++) { try{ XMLHttpReqVerifyCode = new ActiveXObject(MSXML[i]); } catch(e) { } } } XMLHttpReqVerifyCode.open("POST",url, true); XMLHttpReqVerifyCode.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); XMLHttpReqVerifyCode.onreadystatechange = function testVerifyCodeServletResponse(){ if(XMLHttpReqVerifyCode.readyState == 4 && (XMLHttpReqVerifyCode.status == 200 || XMLHttpReqVerifyCode.status == 304)) { if(XMLHttpReqVerifyCode.responseText == 1){ tip.innerHTML = successTip; tip.style.color = "green"; }else if(XMLHttpReqVerifyCode.responseText == 0){ tip.innerHTML = errorTip; tip.style.color = "red"; } } } XMLHttpReqVerifyCode.send("code="+verifyCode); } //ajax前后台交互 function createXMLHttpRequest(XMLHttpReq) { if(window.XMLHttpRequest) { //DOM2浏览器 XMLHttpReq = new XMLHttpRequest(); } else if(window.ActiveXObject) { //使用json语法创建数组 var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP']; for(var i = 0; i < MSXML.length; i++) { try{ XMLHttpReq = new ActiveXObject(MSXML[i]); } catch(e) { } } return XMLHttpReq; } } }TestVerifyCodeServlet与js交互代码为:
package Servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class TestVerifyCodeServlet */ @WebServlet("/TestVerifyCodeServlet") public class TestVerifyCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TestVerifyCodeServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String codeTrue = (String) request.getSession().getAttribute("verifyCode"); String codeInput = request.getParameter("code"); System.out.println(codeInput); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter();//打印流 if(codeInput!=null){ if(codeInput.toUpperCase().equals(codeTrue)){ out.println("1"); }else{ out.println("0"); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }xml代码为
<"1.0" encoding="UTF-8""http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name></display-name> <welcome-file-list> <welcome-file>demo.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>Servlet.VerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/servlet/VerifyCodeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>TestVerifyCodeServlet</servlet-name> <servlet-class>Servlet.TestVerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestVerifyCodeServlet</servlet-name> <url-pattern>/servlet/TestVerifyCodeServlet</url-pattern> </servlet-mapping> </web-app>结果显示:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]