cookie和session頁面隨機數和防止重復提交


http

無狀態的協議,每次請求都是獨立的我們不能存儲第一次訪問的數據

Cookie

實現訪問請求的數據保存

將服務器中的一小段,存入瀏覽器中放在瀏覽器中的cookie中,是存入瀏覽器中。

優點:減少服務器的壓力

缺點:不安全,存儲的數據單一,只能為字符串,可以通過路由器獲得所有的cookie

1. 添加cookie

2. 獲得cookie

3. 解決中文亂碼問題

4. 修改cookie的兩種方式(cookie為鍵值對,key值不能重復,或者cookie.setvalues()

5. 生命周期

(1)默認為添加到瀏覽器和關閉瀏覽器

(2)設置setMaxAge(>0)

package cn.jiedada.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("*.cookie")
public class CookieServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //獲得uri
        String uri = req.getRequestURI();
        //輸出類型
        resp.setContentType("text/html;charset=utf-8");
        //判斷請求
        uri=uri.substring(uri.indexOf("/")+1, uri.indexOf("."));
        if(uri.equals("add")){
            doAdd(req,resp);
        }if(uri.equals("find")){
            doFind(req,resp);
        }
    }

    private void doFind(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cookie[] cookies = req.getCookies();
        //獲得cookie
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            //解碼方式
            value=URLDecoder.decode(value, "UTF-8");
            resp.getWriter().print("<h1>"+name+"--"+value+"</h2>");
        }
    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //解決中文亂碼問題
        Cookie c1 = new Cookie("name", URLEncoder.encode("傑帥", "UTF-8"));
        Cookie c2 = new Cookie("age", "20");
        //創建cookie並且發送到頁面
        resp.addCookie(c1);
        resp.addCookie(c2);
        resp.getWriter().print("<h1>登陸成功</h1>");
    }
}
View Code

作用可以通過cookie來實現再次瀏覽該網頁,然后登陸,判斷里面的cookie值,如果有就直接登陸

Session

Session一次會話的,的創建方式

1通過servlet中的req.getSession()獲得

2. 創建一個jsp

session的使用

Session.setAttribute()

Session.getAttribute()

Session.removeAttribute()

session的注銷

Session.inv

package cn.jiedada.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("*.session")
public class SessionServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        resp.setContentType("text/html;charset=utf-8");
        uri=uri.substring(uri.indexOf("/")+1, uri.indexOf("."));
        if(uri.equals("add")){
            doAdd(req,resp);
        }
    }
    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.setAttribute("name", "tom");
        //session.setMaxInactiveInterval(30);
        resp.sendRedirect("session.jsp");
    }
}
View Code

 

防止重復提交

把隨機數生成的值綁定到前端,然后在Java代碼中刪除這次的綁定參數,這樣就可以在第二次提交的時候隨機數通不過

 

    //通過綁定之獲得隨機數中的隨機值,判斷是否和我們輸入的相同
        String incode = req.getSession().getAttribute("RANDOMCODE_IN_SESSION").toString();
        //清除值,讓他為null防止重復提交
        req.getSession().removeAttribute("RANDOMCODE_IN_SESSION");
        if(code.equals(incode)){

 

 

 

驗證碼

有多種方式這里使用的是uuid的方式,還有雪花函數,等等。。。。

 

package cn.jiedada.controller;

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 java.util.UUID;
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;

@WebServlet("/randomCode")
public class RandomCode1Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //生成隨機數
        String randomCode = UUID.randomUUID().toString().substring(0, 5);

        //把隨機數放進Session中
        req.getSession().setAttribute("RANDOMCODE_IN_SESSION", randomCode);

        //創建圖片對象
        int width = 100;
        int height = 30;
        int imageType = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(width, height, imageType);

        //畫板
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        //繪制一個實心的矩形
        g.fillRect(1, 1, width - 2, height - 2);

        //把隨機數畫進圖片中
        g.setColor(Color.BLUE);//設置隨機數的顏色
        Font font = new Font("宋體", Font.BOLD + Font.ITALIC, 25);
        g.setFont(font);//設置隨機數的字體和大小
        g.drawString(randomCode, 10, 23);
        //干擾線
        g.setColor(Color.GRAY);
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            g.fillRect(r.nextInt(width), r.nextInt(height), 2, 2);
        }

        //關閉
        g.dispose();
        //把圖片對象以流的方式保存出去
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM