Session可避免表单的重复提交:实现一次表单提交,可避免恶意提交;

1.首先建立一个Servlet类:ValidateColorServlet,里边有获取验证码的方法,并且验证码是大小写区分:

public class ValidateColorServlet extends HttpServlet {

    public static final String CHECK_CODE_KEY = "CHECK_CODE_KEY";

    private static final long serialVersionUID = 1L;

    //设置验证图片的宽度, 高度, 验证码的个数
private int width = 152;
private int height = 40;
private int codeCount = 6; //验证码字体的高度
private int fontHeight = 4; //验证码中的单个字符基线. 即:验证码中的单个字符位于验证码图形左上角的 (codeX, codeY) 位置处
private int codeX = 0;
private int codeY = 0; //验证码由哪些字符组成
char [] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789".toCharArray(); //初始化验证码图形属性
public void init(){
fontHeight = height - 2;
codeX = width / (codeCount + 2);
codeY = height - 4;
} public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//定义一个类型为 BufferedImage.TYPE_INT_BGR 类型的图像缓存
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); //在 buffImg 中创建一个 Graphics2D 图像
Graphics2D graphics = null;
graphics = buffImg.createGraphics(); //设置一个颜色, 使 Graphics2D 对象的后续图形使用这个颜色
graphics.setColor(Color.WHITE); //填充一个指定的矩形: x - 要填充矩形的 x 坐标; y - 要填充矩形的 y 坐标; width - 要填充矩形的宽度; height - 要填充矩形的高度
graphics.fillRect(0, 0, width, height); //创建一个 Font 对象: name - 字体名称; style - Font 的样式常量; size - Font 的点大小
Font font = null;
font = new Font("", Font.BOLD, fontHeight);
//使 Graphics2D 对象的后续图形使用此字体
graphics.setFont(font); graphics.setColor(Color.BLACK); //绘制指定矩形的边框, 绘制出的矩形将比构件宽一个也高一个像素
graphics.drawRect(0, 0, width - 1, height - 1); //随机产生 15 条干扰线, 使图像中的认证码不易被其它程序探测到
Random random = null;
random = new Random();
graphics.setColor(Color.GREEN);
for(int i = 0; i < 55; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(20);
int y1 = random.nextInt(20);
graphics.drawLine(x, y, x + x1, y + y1);
} //创建 randomCode 对象, 用于保存随机产生的验证码, 以便用户登录后进行验证
StringBuffer randomCode;
randomCode = new StringBuffer(); for(int i = 0; i < codeCount; i++){
//得到随机产生的验证码数字
String strRand = null;
strRand = String.valueOf(codeSequence[random.nextInt(36)]); //把正在产生的随机字符放入到 StringBuffer 中
randomCode.append(strRand); //用随机产生的颜色将验证码绘制到图像中
graphics.setColor(Color.BLUE);
graphics.drawString(strRand, (i + 1)* codeX, codeY);
} //再把存放有所有随机字符的 StringBuffer 对应的字符串放入到 HttpSession 中
request.getSession().setAttribute(CHECK_CODE_KEY, randomCode.toString()); //禁止图像缓存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0); //将图像输出到输出流中
ServletOutputStream sos = null;
sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}

2.index.jsp页面,输入用户名字,输入验证码:checkCode:<input type="text" name="CHECK_CODE_PARAM_NAME"/>;获取验证码:是以插入图片的形式获取的<img alt="" src="<%=request.getContextPath() %>/validateColorServlet">,然后form表单提交到Servlet类:CheckCodeServlet

<%@ 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">
<title>Insert title here</title>
</head>
<body>
<font color="red">
<%=session.getAttribute("message")==null ? "" : session.getAttribute("message") %>
</font> <form action="<%=request.getContextPath() %>/checkCodeServlet" method="post"> name:<input type="text" name="name"/>
<br><br>
checkCode:<input type="text" name="CHECK_CODE_PARAM_NAME"/> <img alt="" src="<%=request.getContextPath() %>/validateColorServlet">
<br><br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

3.建立一个Servlet类:CheckCodeServlet,获取表单输入的验证码和通过session的getsession()方法获取系统给予的验证码,并进行判断,看是否相等,然后重定向到index.jsp页面,输出结果;

public class CheckCodeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. 获取请求参数: CHECK_CODE_PARAM_NAME
String paramCode = request.getParameter("CHECK_CODE_PARAM_NAME"); //2. 获取 session 中的 CHECK_CODE_KEY 属性值
String sessionCode = (String)request.getSession().getAttribute("CHECK_CODE_KEY"); System.out.println(paramCode);
System.out.println(sessionCode); //3. 比对. 看是否一致, 若一致说明验证码正确, 若不一致, 说明验证码错误
if(!(paramCode == null && !paramCode.equals(sessionCode))){
request.getSession().setAttribute("message", "验证码不一致!");
response.sendRedirect(request.getContextPath() + "/check/index.jsp");
return;
} System.out.println("受理请求!"); } }

4.lib下的web.xml文件为:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="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" id="WebApp_ID" version="2.5"> <servlet>
<description></description>
<display-name>ValidateColorServlet</display-name>
<servlet-name>ValidateColorServlet</servlet-name>
<servlet-class>com.lanqiao.javatest.ValidateColorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateColorServlet</servlet-name>
<url-pattern>/validateColorServlet</url-pattern>
</servlet-mapping> <servlet>
<description></description>
<display-name>CheckCodeServlet</display-name>
<servlet-name>CheckCodeServlet</servlet-name>
<servlet-class>com.lanqiao.javatest.CheckCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckCodeServlet</servlet-name>
<url-pattern>/checkCodeServlet</url-pattern>
</servlet-mapping>
</web-app>

利用Session实现一次验证码的更多相关文章

  1. 利用 canvas 破解 某拖动验证码

    利用 canvas 破解 某拖动验证码 http://my.oschina.net/u/237940/blog/337194

  2. 学习笔记:利用GDI+生成简单的验证码图片

    学习笔记:利用GDI+生成简单的验证码图片 /// <summary> /// 单击图片时切换图片 /// </summary> /// <param name=&quo ...

  3. 【转】asp.net中利用session对象传递、共享数据[session用法]

    来自:http://blog.unvs.cn/archives/session-transfer-method.html 下面介绍Asp.net中利用session对象传递.共享数据用法: 1.传递值 ...

  4. asp.net中利用session对象传递、共享数据[session用法]

    下面介绍Asp.net中利用session对象传递.共享数据用法: 1.传递值: 首先定义将一个文本值或单独一个值赋予session,如下: session[“name”]=textbox1.text ...

  5. python利用django实现简单的登录和注册,并利用session实现了链接数据库

    利用session实现与数据库链接,登录模块(在views.py) def login(request): # return HttpResponseRedirect('/') # 判断是否post方 ...

  6. 利用session防止表单重复提交

    转自:http://www.cnblogs.com/xdp-gacl/p/3859416.html 利用Session防止表单重复提交 对于[场景二]和[场景三]导致表单重复提交的问题,既然客户端无法 ...

  7. 利用Session实现三天免登陆

    什么是Session Session:在计算机中,尤其是在网络应用中,称为“会话控制”.(百度百科) Session:服务器端的数据存储技术. Session要解决什么问题 一个用户的不同请求(重定位 ...

  8. 利用cookies跳过登陆验证码

    前言在爬取某些网页时,登陆界面时经常遇到的一个坎,而现在大多数的网站在登陆时都会要求用户填写验证码.当然,我们可以设计一套机器学习的算法去破解验证码,然而,验证码的形式多种多样,稍微变一下(有些甚至是 ...

  9. .net C# 利用Session防重复点击防重复提交

    <body>    <form id="form1" runat="server">    <div>        < ...

随机推荐

  1. F面经prepare:strstr变种

    * Given an integer k>=1 and two strings A and B (length ~n each); * Figure out if there is any co ...

  2. JAVA-语法-运算符

    1.赋值运算符  =  (优先级较低) 2.算数运算符  +  —  *  /  % 3.字符串连接运算   +  (把其他类型转成字符串并和字符串类型进行连接) 4.扩展赋值运算符   +=   — ...

  3. 体验Java的封装性

    package com.cnblogs.java; //体验Java的封装性 /* * 如下的人类年龄赋值-300岁,显然很不合理,这种直接对类的属性赋值,有时候虽然不合理但却会编译通过. * 所以我 ...

  4. sdutoj 2607 Mountain Subsequences

    http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2607 Mountain Subsequence ...

  5. [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  6. C# 问题解决思路--《数组bytes未定义》,ASP.NET页面加载顺序

    好久没写博客了,废话不多说,直接说问题. 问题发生情况,首先这个是老项目,然后我是第一次修改.当我解决了各种引用,数据库配置之后等类似的问题,我启动的项目的时候,无任何问题,但是当我点击页面的按钮的时 ...

  7. linux第2天 信号 wait

    孤儿进程和僵尸进程 如果父进程先退出,子进程还没退出那么子进程的父进程将变为init进程.(注:任何一个进程都必须有父进程) 如果子进程先退出,父进程还没退出,那么子进程必须等到父进程捕获到了子进程的 ...

  8. HDU 1402 A * B Problem Plus(FFT)

    Problem Description Calculate A * B.   Input Each line will contain two integers A and B. Process to ...

  9. struts一些实用常量配置_2015.01.04

  10. @有两个含义:1,在参数里,以表明该变量为伪参数 ,在本例中下文里将用@name变量代入当前代码中2,在字串中,@的意思就是后面的字串以它原本的含义显示,如果不

    @有两个含义:1,在参数里,以表明该变量为伪参数 ,在本例中下文里将用@name变量代入当前代码中 2,在字串中,@的意思就是后面的字串以它原本的含义显示,如果不加@那么需要用一些转义符\来显示一些特 ...