关闭

web路径、表单重复提交(2种方法)、验证码

1092人阅读 评论(0) 收藏 举报
分类:

绝对路径:相对于当前WEB应用的的根路径,路径都带上contextPath
http://localhost:8080/day01/a.jsp 绝对
http://localhost:8080/a.jsp 错误

web中的/代表啥?
这里写图片描述

表单的重复提交

1、表单提交到一个servlet,servlet转发到一个jsp页面,而浏览器地址还是servlet的路径,在相应页面刷新
2、在相应页面还没有到达时,重复点击提交按钮
3、点击返回,在点击提交

<在原表单页面中,生成一个随机的token,将其放入到session属性(setAttribute)和隐藏域中(hidden)
<在目标servlet中,获取session值和隐藏域中的token值
<如果2个值一致,受理请求,并把session域中的token属性清除,若不一致,则提示重复提交

index.jsp

<body>
    <%
        String tokenValue = new Date().getTime() + "";
        session.setAttribute("token", tokenValue );
    %>
    <form action="<%=request.getContextPath()%>/tokenServlet"
        method="post">
        <input type="hidden" name="token" value="<%=tokenValue%>" /> 
        name:<input type="text" name="name" /> 
             <input type="submit" value="Submit" />
    </form>
</body>

TokenServlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Object token = session.getAttribute("token");

        String tokenValue = request.getParameter("token");

        System.out.println(token);
        System.out.println(tokenValue);

        if (token != null && token.equals(tokenValue)) {
            session.removeAttribute("token");
        }else{
            response.sendRedirect(request.getContextPath()+"/token/token.jsp");
            return;
        }
        String name = request.getParameter("name");
        System.out.println("name:"+name);

        response.sendRedirect(request.getContextPath()+"/token/success.jsp");
    }

success.jsp中是提示 成功的一句话
token.jsp中是提示重复提交

http://localhost:8080/day01/token/index.jsp
这里写图片描述

http://localhost:8080/day01/token/success.jsp
这里写图片描述

http://localhost:8080/day01/token/token.jsp
这里写图片描述

如果返回到http://localhost:8080/day01/token/index.jsp页面,在提交前,进行刷新页面,在输入值,进行提交,不算重复请求,因为又是一个新的请求

表单的重复提交,代码升级
我们可以将来token != null && token.equals(tokenValue)逻辑放到一个类中统一实现

TokenProcessor这个实现原理跟楼上的例子本质是一样的,也是请求后,移除 session.removeAttribute(“token”);

package com.safly;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class TokenProcessor {
    private static final String TOKEN_KEY = "TOKEN_KEY";
    private static final String TRANSACTION_TOKEN_KEY = "TRANSACTION_TOKEN_KEY";
    private static TokenProcessor instance = new TokenProcessor();
    private long previous;
    protected TokenProcessor() {
        super();
    }

    public static TokenProcessor getInstance() {
        return instance;
    }
    public synchronized boolean isTokenValid(HttpServletRequest request) {
        return this.isTokenValid(request, false);
    }
    public synchronized boolean isTokenValid(HttpServletRequest request,
            boolean reset) {
        HttpSession session = request.getSession(false);

        if (session == null) {
            return false;
        }
        String saved = (String) session.getAttribute(TRANSACTION_TOKEN_KEY);
        if (saved == null) {
            return false;
        }
        if (reset) {
            this.resetToken(request);
        }
        String token = request.getParameter(TOKEN_KEY);

        if (token == null) {
            return false;
        }
        return saved.equals(token);
    }
    public synchronized void resetToken(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(TRANSACTION_TOKEN_KEY);
    }
    public synchronized String saveToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String token = generateToken(request);
        if(token != null) {
            session.setAttribute(TRANSACTION_TOKEN_KEY, token);
        }
        return token;
    }
    public synchronized String generateToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return generateToken(session.getId());
    }
    public synchronized String generateToken(String id) {
        try {
            long current = System.currentTimeMillis();
            if (current == previous) {
                current++;
            }
            previous = current;
            byte[] now = new Long(current).toString().getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(id.getBytes());
            md.update(now);
            return toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
    private String toHex(byte[] buffer) {
        StringBuffer sb = new StringBuffer(buffer.length * 2);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
        }
        return sb.toString();
    }
}

index.jsp

<body>
    <form action="<%=request.getContextPath()%>/tokenServlet"
        method="post">
        <input type="hidden" name="TOKEN_KEY" value="<%=TokenProcessor.getInstance().saveToken(request)%>" /> 
        name:<input type="text" name="name" /> 
             <input type="submit" value="Submit" />
    </form>
</body>

TokenServlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean tokenValid = TokenProcessor.getInstance().isTokenValid(request);
        if (tokenValid) {
            TokenProcessor.getInstance().resetToken(request);   
        }else{
            response.sendRedirect(request.getContextPath()+"/token/token.jsp");
            return;
        }
        String name = request.getParameter("name");
        System.out.println("name:"+name);
        response.sendRedirect(request.getContextPath()+"/token/success.jsp");
    }

验证码
验证码是经常见得,它其实没有那么神秘,跟表单重复提交的实现原理相似

index.jsp

<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"/>
        checkCode: <input type="text" name="CHECK_CODE_PARAM_NAME"/> 
        <img alt="" src="<%= request.getContextPath() %>/validateColorServlet"> 
        <input type="submit" value="Submit"/>
    </form>
</body>

CheckCodeServlet

package com.safly;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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("受理请求!");
    }
}

ValidateColorServlet

package com.safly; 

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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();
    }
}

验证码正确的情况
这里写图片描述
这里写图片描述

验证码输错的情况:
这里写图片描述
服务端控制台输出:
sdfsdf
JZUUFO

验证码的流程是什么?
浏览器访问http://localhost:8080/day01/check/index.jsp
定义一个验证码输入框的getParameter
checkCode:
然后验证码图片

<img alt="" src="<%= request.getContextPath() %>/validateColorServlet"> 

访问ValidateColorServlet,在浏览器输出验证码图片
在ValidateColorServlet中
//再把存放有所有随机字符的 StringBuffer 对应的字符串放入到 HttpSession 中
request.getSession().setAttribute(CHECK_CODE_KEY, randomCode.toString());

通过Set-Cookie方式在Response Headers中返回
当输入验证码完毕,点击提交,就跳转到CheckCodeServlet去验证
String paramCode = request.getParameter(“CHECK_CODE_PARAM_NAME”)获取输入的验证码
String sessionCode = (String)request.getSession().getAttribute(“CHECK_CODE_KEY”);获取Response Headers中返回的值

然后2者一致说明验证成功!!
错误的话request.getSession().setAttribute(“message”, “验证码不一致!”);
重定向到index.jsp中进行页面输错提示

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:375994次
    • 积分:7762
    • 等级:
    • 排名:第2819名
    • 原创:417篇
    • 转载:5篇
    • 译文:1篇
    • 评论:66条
    友情链接
    最新评论