今天在调试项目的时候发现,在提交表单的时候的验证码有问题,问题是这样的:就是通过debug模式查看得知:jsp页面生成的验证码和表单输入的页面输入的一样,但是到后台执行的时候,你会发现他们是不一样的,现在上图看看:
1.这是表单提交的时候:
2.这是后台得到的生成的验证码:
3.这是后台得到输入的验证码:
这样的问题还是头一次出现,以前没遇到过,经过google,baidu,最后得知是这样的:因为加载jsp页面比加载session快一些
那怎么办才能解决这个办法呢,
又经过多次搜索,思考,实践,终于想出了个好办法
1.在jsp页面用js生成验证码并保存在变量中,验证码作为参数传到java(继承了HttpServlet)类
2.根据jsp页面中传过来的验证码画出一个有干扰线或干扰点的图片
3.在WEB-INF/web.xml中配置 servlet
4.在jsp页面调用配置好的servlet,一般是通过<img src="servlet名" id="code"/>调用
5.提交数据之前验证
<form onsubmit="return validate();"……/>
局部刷新验证码:<a href="#" onclick="javascript:show();return false;">看不清,换一张!</a>-----return false;很重要啊
下面直接附上我的例子:
截图如下:
代码如下:
1.JAVA类:CodeServlet.java:
[java] view plain copy
print?
- package cn.gov.csrc.servlet;
- import java.awt.Color;
- import java.awt.Font;
- import java.awt.Graphics;
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import java.util.Random;
- import javax.servlet.ServletException;
- 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 CodeServlet extends HttpServlet {
- /**
- * 产生验证码图片
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("image/jpeg");
- response.setHeader("Cache-Control", "no-cache");
- response.setHeader("Pragma", "No-cache");
- response.setDateHeader("Expires", 0L);
- int width = 80;
- int height = 30;
- BufferedImage image = new BufferedImage(width, height, 1);
- Graphics g = image.getGraphics();
- Random random = new Random();
- g.setColor(getRandColor(200, 250));
- g.fillRect(0, 0, width, height);
- g.setFont(new Font("Arial", 0, 25));
- g.setColor(getRandColor(160, 200));
- for (int i = 0; i < 155; i++) {
- int x = random.nextInt(width + 100);
- int y = random.nextInt(height + 100);
- int xl = random.nextInt(10);
- int yl = random.nextInt(12);
- g.drawOval(x, y, x + xl, y + yl);
- }
- String code = request.getParameter("code");
- String sRand = code;
- for (int i = 0; i < sRand.length(); i++) {
- String rand = sRand.substring(i, i + 1);
- g.setColor(new Color(20 + random.nextInt(110), 20 + random
- .nextInt(110), 20 + random.nextInt(110)));
- g.drawString(rand, 14 * i + 5, 25);
- }
- g.dispose();
- javax.servlet.ServletOutputStream imageOut = response.getOutputStream();
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut);
- encoder.encode(image);
- }
- private Color getRandColor(int fc, int bc) {
- Random random = new Random();
- if (fc > 255)
- fc = 255;
- if (bc > 255)
- bc = 255;
- int r = fc + random.nextInt(bc - fc);
- int g = fc + random.nextInt(bc - fc);
- int b = fc + random.nextInt(bc - fc);
- return new Color(r, g, b);
- }
- }
package cn.gov.csrc.servlet;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;import javax.servlet.ServletException;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 CodeServlet extends HttpServlet { /** * 产生验证码图片 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0L); int width = 80; int height = 30; BufferedImage image = new BufferedImage(width, height, 1); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Arial", 0, 25)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width + 100); int y = random.nextInt(height + 100); int xl = random.nextInt(10); int yl = random.nextInt(12); g.drawOval(x, y, x + xl, y + yl); } String code = request.getParameter("code"); String sRand = code; for (int i = 0; i < sRand.length(); i++) { String rand = sRand.substring(i, i + 1); g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 14 * i + 5, 25); } g.dispose(); javax.servlet.ServletOutputStream imageOut = response.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut); encoder.encode(image); } private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); }}
2.Web.xml文件:
[html] view plain copy
print?
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5" 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_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>CodeServlet</servlet-name>
- <servlet-class>cn.gov.csrc.servlet.CodeServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>CodeServlet</servlet-name>
- <url-pattern>/CodeServlet</url-pattern>
- </servlet-mapping>
- </web-app>
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 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_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>CodeServlet</servlet-name> <servlet-class>cn.gov.csrc.servlet.CodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CodeServlet</servlet-name> <url-pattern>/CodeServlet</url-pattern> </servlet-mapping></web-app>
3.index.jsp:
[javascript] view plain copy
print?
- <%@ 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">
- <script language="javascript" type="text/javascript">
- var code ; //在全局 定义验证码
- function createCode(){
- code = "";
- var codeLength = 5;//验证码的长度
- //所有候选组成验证码的字符,可以用中文
- var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,‘A‘,‘B‘,‘C‘,
- ‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,‘O‘,‘P‘,
- ‘Q‘,‘R‘,‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘,‘a‘,‘b‘,‘c‘,
- ‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘,‘l‘,‘m‘,‘n‘,‘o‘,‘p‘,
- ‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘);
- for(var i=0;i<codeLength;i++){
- var charIndex = Math.floor(Math.random()*60);
- code +=selectChar[charIndex];
- }
- return code;
- }
- function validate (){
- var inputCode = document.getElementById("vcode").value.toLowerCase();
- if(inputCode.length <=0){
- alert("请输入验证码!");
- return false;
- }
- else if(inputCode != code.toLowerCase()){
- alert("验证码输入错误!");
- show();//刷新验证码
- return false;
- }else{
- alert("^-^ OK");
- return true;
- }
- }
- function show(){
- //显示验证码
- document.getElementById("code").src="CodeServlet?code="+createCode();
- }
- window.onload = function() {
- //document.onload=show();
- show();//页面加载时加载验证码
- //这时无论在ie还是在firefox中,js没有加载完,页面的东西是不会被执行的;
- }
- </script>
- </head>
- <body>
- <form onsubmit="return validate();" action="" method="post">
- <h3>jsp+js+servlet实现验证码</h3>
- <br /> 用户名:<input type="text" name="" /><br /> 请输入验证码: <input
- type="text" id="vcode" style="width: 60;" maxLength="5" /> <img
- src="" id="code" /> <a href="#" mce_href="#"
- onclick="javascript:show();return false;">看不清,换一张!</a><br /> <input
- type="submit" />
- </form>
- </body>
- </html>
<%@ 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"><script language="javascript" type="text/javascript">var code ; //在全局 定义验证码 function createCode(){ code = ""; var codeLength = 5;//验证码的长度 //所有候选组成验证码的字符,可以用中文 var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,‘A‘,‘B‘,‘C‘, ‘D‘,‘E‘,‘F‘,‘G‘,‘H‘,‘I‘,‘J‘,‘K‘,‘L‘,‘M‘,‘N‘,‘O‘,‘P‘, ‘Q‘,‘R‘,‘S‘,‘T‘,‘U‘,‘V‘,‘W‘,‘X‘,‘Y‘,‘Z‘,‘a‘,‘b‘,‘c‘, ‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘,‘l‘,‘m‘,‘n‘,‘o‘,‘p‘, ‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘); for(var i=0;i<codeLength;i++){ var charIndex = Math.floor(Math.random()*60); code +=selectChar[charIndex]; } return code; } function validate (){ var inputCode = document.getElementById("vcode").value.toLowerCase(); if(inputCode.length <=0){ alert("请输入验证码!"); return false; } else if(inputCode != code.toLowerCase()){ alert("验证码输入错误!"); show();//刷新验证码 return false; }else{ alert("^-^ OK"); return true; } } function show(){ //显示验证码 document.getElementById("code").src="CodeServlet?code="+createCode(); } window.onload = function() { //document.onload=show(); show();//页面加载时加载验证码 //这时无论在ie还是在firefox中,js没有加载完,页面的东西是不会被执行的; } </script></head><body> <form onsubmit="return validate();" action="" method="post"> <h3>jsp+js+servlet实现验证码</h3> <br /> 用户名:<input type="text" name="" /><br /> 请输入验证码: <input type="text" id="vcode" style="width: 60;" maxLength="5" /> <img src="" id="code" /> <a href="#" mce_href="#" onclick="javascript:show();return false;">看不清,换一张!</a><br /> <input type="submit" /> </form></body></html>
原文地址:https://www.cnblogs.com/jpfss/p/8444654.html