• java四大会话技术


    未经作者允许,不得转载
    第一cookie技术
    常用方法:

    • new Cookie(),构造一个cookie
    • getName() ,获取cookie的名字
    • getValue () ,取到具体cookie的值
    • setMaxAge(), 设置cookie过期时间 单位为秒
    • getpath() ,取cookie路径
      -需要注意的地方:
      setMaxAge();当值为0时,即为删除本地cookie文件
      还要注意cookie文件path路径必须一致
      代码事例:
    package myCookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Date;
    
    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(urlPatterns = "/mycookie")
    public class myCookieDemo extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // super.doGet(req, resp);
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // super.doPost(req, resp);
            // 通用设置页面编码
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            // 控制文字输出流
            PrintWriter writer = resp.getWriter();
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                writer.write("您上次访问的时间是:");
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    if (cookie.getName().equals("lasttime")) {
                        String value = cookie.getValue();
                        Date date = new Date(Long.parseLong(value));
                        writer.println("cookie的路径"+cookie.getPath());
                        writer.println(date.toString());
                    }
                }
    
            } else {
                writer.print("欢迎第一次访问本页面!");
            }
            //向系统增加cookie
            Cookie cookie = new Cookie("lasttime", System.currentTimeMillis() + "");
            //让session由内存写入到硬盘中    单位时间为 s秒  一天 60*60*24
            cookie.setMaxAge(20);
            resp.addCookie(cookie);
        }
    
    }
    

    这里写图片描述

    • 设置中文编码问题
    • -
        //cookie中采用中文编码问题 Urlencoder处理
           new Cookie("username", URLEncoder.encode("亮剑精神", "UTF-8"));
            ///解码
           URLEncoder.encode("cookie[i].getValue()", "UTF-8");

    地址重写
    应用方向:在浏览器不允许使用cookie时,那么就可以采用这个办法进行地址的重写
    重要方法:resp.encodeURL 之前必须初始化会话 getSession()

    注:浏览器默认会使用含有cookie的办法使用 代码测试很多次数没有成功,必须关闭浏览器cookie设置

    package Urlencode;
    
    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;
    @WebServlet(urlPatterns="/myencode")
    public class myEncode extends HttpServlet{
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
        //  super.doGet(req, resp);
            doPost(req, resp);
        }
    
        @SuppressWarnings("deprecation")
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            //super.doPost(req, resp);
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter writer = resp.getWriter();
            //必须手动初始化回话
            req.getSession();
            String str = resp.encodeURL("/SessionTchCookies/index.jsp");
            String str2 = resp.encodeURL("/SessionTchCookies/error.jsp");
            String url = resp.encodeRedirectURL("/SessionTchCookies/index.jsp");
    
            writer.print("<a href='" + url + "'>购买</a><br/>");  
            writer.print("<a href='" + str2 + "'>结账</a>");  
            writer.close();
    
    
    
    
    
    
    
        }
    
    
    }
    

    这里写图片描述


    关于重写技术在很多框架都有实现

    • struts2 <html:rewrite action='logout'/> html:rewrite
    • 类似的还有 <html:link/> <html:from />

    • jstl中 :<c:url /> 来进行地址重写


    表单隐藏技术的实现

    5.表单隐藏域
    <form action="" method="">
    相关的表单控件...
    
    <input type="hidden" name="参数名1" value="参数值1"/>
    ...
    <input type="hidden" name="jsessionid" value="xxxxx"/>
    <input type="hidden" name="参数名n" value="参数值n"/>
    </form>
    
    

    会话的实现

    充电类:httpservletsession . getSession() 取得会话对象

    setAttribute(“属性名”,”属性值”) 根据属性名设值
    getAttribute(“属性名”) 根据属性名 获取对应的值
    removeAttribute(“属性名”) 根据属性名删除

    getId():获取Session唯一的ID
    invalidate():使HttpSession对象失效
    setMaxInactiveInterval(时间):设置Session过期时间,单位是秒
    getCreationTime():获取HttpSession对象创建时间
    getLastAccessedTime():获取HttpSession最近一次请求时间

    <%@ page language="Java" contentType="text/html; charset=UTF-8"
        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">
     </head>
     <body>
     首页
     <% 
               out.print("会话是isnew"+session.isNew());
               out.print(session.getCreationTime());
               /* 设置会话的过期时间   在控制的时候建设
                                 方法1:可以在多个页面进行传值控制  set**  get***
                                 方法2:可以在设置一个相对时间比较长的值   然后在不同的页面进行时间属性的更新
               */
               session.setMaxInactiveInterval(60);
               //手动控制使session过期
               session.invalidate();
    
     %>
     </body>
    </html>
  • 相关阅读:
    Kali,CentOS 配置静态网络与开启SSH服务【附VMware中配置】
    httpHelper请求辅助类
    请求后的数据处理
    Viewcontroller基类
    上拉下拉基类
    获取cell中的button在整个屏幕上的位置
    Object-C反射读取实体属性和值
    xcode在代码中查找中文
    编写xcode5插件需要增加DVTPlugInCompatibilityUUIDs
    c# 扩展方法
  • 原文地址:https://www.cnblogs.com/dgwblog/p/7635209.html
Copyright © 2020-2023  润新知