zoukankan      html  css  js  c++  java
  • 路径问题以及cookie详解

    1.路径问题:

    注意 .代表执行程序的文件夹路径,在tomcat中也就是bin目录,所以要用this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");得到绝对路径;

    代码练习:

    package com.http.path;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Properties;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class PathDemo extends HttpServlet {
    
        public PathDemo() {
            super();
        }
    
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setCharacterEncoding("utf-8");
            request.setCharacterEncoding("utf-8");
            
            //给服务器使用的:   / 表示在当前web应用的根目录(webRoot下)
            //request.getRequestDispatcher("/target.html").forward(request, response);
            
            //给浏览器使用的: /  表示在webapps的根目录下
            //response.sendRedirect("/MyWeb/target.html");
            
            String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
            //this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
            System.out.println(path);
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(path)));
            
            String user = properties.getProperty("user");
            String passwd = properties.getProperty("passwd");
            System.out.println("user = " + user + "
    passwd = " + passwd);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    2.Cooke技术

    2.1 特点

    Cookie技术:会话数据保存在浏览器客户端。

    2.2 Cookie技术核心

    Cookie类:用于存储会话数据

    1)构造Cookie对象

    Cookie(java.lang.String name, java.lang.String value)

    2)设置cookie

    void setPath(java.lang.String uri)   :设置cookie的有效访问路径

    void setMaxAge(int expiry)  设置cookie的有效时间

    void setValue(java.lang.String newValue) :设置cookie的值

    3)发送cookie到浏览器端保存

    void response.addCookie(Cookie cookie)  : 发送cookie

    4)服务器接收cookie

    Cookie[] request.getCookies()  : 接收cookie

    2.3 Cookie原理

    1)服务器创建cookie对象,把会话数据存储到cookie对象中。

    new Cookie("name","value");

    2 服务器发送cookie信息到浏览器

    response.addCookie(cookie);

    举例: set-cookie: name=eric  (隐藏发送了一个set-cookie名称的响应头)

    3)浏览器得到服务器发送的cookie,然后保存在浏览器端。

    4)浏览器在下次访问服务器时,会带着cookie信息

        举例: cookie: name=eric  (隐藏带着一个叫cookie名称的请求头)

    5)服务器接收到浏览器带来的cookie信息

    request.getCookies();

    2.4 Cookie的细节

    1void setPath(java.lang.String uri)   :设置cookie的有效访问路径。有效路径指的是cookie的有效路径保存在哪里,那么浏览器在有效路径下访问服务器时就会带着cookie信息,否则不带cookie信息。

    2void setMaxAge(int expiry)  设置cookie的有效时间。

    正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。

    负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!

    零:表示删除同名的cookie数据

    3Cookie数据类型只能保存非中文字符串类型的。可以保存多个cookie,但是浏览器一般只允许存放300Cookie,每个站点最多存放20Cookie,每个Cookie的大小限制为4KB

    在下面查了下,cookie也可以存中文字符串,可以用URLEncoder类中的encode方法编码,然后用URLDecoder.decode方法解码

    cookie的简单练习:

    package com.http.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class CookieDemo1 extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public CookieDemo1() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            Cookie cookie = new Cookie("name", "handsomecui");
            Cookie cookie2 = new Cookie("email", "handsomecui@qq.com");
            cookie2.setPath("/Test");
            //cookie.setMaxAge(10);//不会受到浏览器关闭的影响
            cookie.setMaxAge(-1);//cookie保存在浏览器内存,关闭移除
            //cookie.setMaxAge(0);//删除同名cookie
            response.addCookie(cookie);
            response.addCookie(cookie2);
            System.out.println(request.getHeader("cookie"));
            Cookie[] cookies = request.getCookies();
            if(cookies == null){
                System.out.println("没有cookie");
            }
            else{
                for(Cookie acookie : cookies){
                    System.out.println(acookie.getName() + "是" + acookie.getValue());
                }
            }
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    2.5 案例- 显示用户上次访问的时间

    代码:

    package com.http.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Time;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ShowTime extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        private int cnt = 0;
        public ShowTime() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        private String Isexist(HttpServletRequest request){
            Cookie[] cookies = request.getCookies();
            if(cookies == null){
                return null;
            }
            for(Cookie acookie:cookies){
                if("lasttime".equals(acookie.getName())){
                    return acookie.getValue();
                }
            }
            return null;
        }
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            cnt++;
            response.setCharacterEncoding("gb2312");
            request.setCharacterEncoding("gb2312");
            
            response.getWriter().write("您好,这是您第" + cnt + "次访问本站
    ");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            
            String str = format.format(new Date());
            Cookie cookie = new Cookie("lasttime", str);
            response.addCookie(cookie);
            String lasttime = Isexist(request);
            if(lasttime != null){
                response.getWriter().write("您上次访问的时间是:" + lasttime + "
    ");
            }else{
                
            }
            response.getWriter().write("当前时间是:" + str + "
    ");
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    2.6 案例-查看用户浏览器过的商品

    思路:ListServlet展示商品列表,Detailservlet展示商品的详细信息,最近浏览的商品,用一个hashset存储MySet类,取出前三个不重复的即可,cookie存放最近浏览的商品编号,用逗号隔开;

    product类:

    package com.common.product;
    
    import java.util.ArrayList;
    
    public class Product {
        private static ArrayList<Product>arrayList;
        private int id;
        private String name;
        private String type;
        private double price;
        static{
            arrayList = new ArrayList<Product>();
            for(int i = 0; i < 10; i++){
                Product product = new Product(i + 1, "笔记本"+(i + 1), "LN00"+(i+1), 35+i);
                arrayList.add(product);
            }
        }
        public static ArrayList<Product> getArrayList() {
            return arrayList;
        }
        @Override
        public String toString() {
            return "id=" + id + ", name=" + name + ", type=" + type
                    + ", price=" + price ;
        }
        public Product(int id, String name, String type, double price) {
            super();
            this.id = id;
            this.name = name;
            this.type = type;
            this.price = price;
        }
        public Product() {
            super();
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        public Product getValueById(int p) {
            for(int i = 0; i < arrayList.size(); i++){
                if(arrayList.get(i).getId() == p){
                    return arrayList.get(i);
                }
            }
            return null;
        }
        
    }

    MySet类:由编号和商品名构成,主要是为了hashset的去重与排序;

    package com.common.tool;
    
    import java.util.HashSet;
    
    public class MySet{
        private int id;
        private String name;
        public int getId() {
            return id;
        }
        @Override
        public boolean equals(Object o) {
            // TODO Auto-generated method stub
            MySet myset = (MySet)o;
            return myset.getName().equals(this.getName());
        }
        @Override
        public int hashCode() {
            // TODO Auto-generated method stub
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public MySet(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
        public MySet() {
            super();
        }
        
    }

    ListServlet:

    package com.http.servlet;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.common.product.Product;
    
    
    public class ListServlet extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public ListServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            Product product = new Product();
            String html = "";
            html+=("<html>");
            html+=("<head>");
            html+=("<meta charset='utf-8'/>");
            
            html+=("<title>");
            html+=("商品列表");
            html+=("</title>");
            html+=("</head>");
            html+=("<body>");
            html+=("<table align='center' border='1'>");
            html+=("<tr>");
            html+=("<th>");
            html+=("编号");
            html+=("</th>");
            html+=("<th>");
            html+=("商品名称");
            html+=("</th>");
            html+=("<th>");
            html+=("商品型号");
            html+=("</th>");
            html+=("<th>");
            html+=("商品价格");
            html+=("</th>");
            html+=("</tr>");
            ArrayList<Product> list = new Product().getArrayList();
            for(int i = 0; i < list.size(); i++){
                html+=("<tr>");
                html+=("<td>");
                html+=("" + list.get(i).getId());
                html+=("</td>");
                html+=("<td>");
                html+=("<a href = '"+ request.getContextPath() +"/DetailServlet"+"?id="+list.get(i).getId()+"'>" + list.get(i).getName() + "</a>");
                html+=("</td>");
                html+=("<td>");
                html+=(list.get(i).getType());
                html+=("</td>");
                html+=("<td>");
                html+=("" + list.get(i).getPrice());
                html+=("</td>");
                html+=("</tr>");
            }
            html+=("</table>");
            html+=("最近浏览过的商品: " + "<br/>");
            String recentview = null;
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if("RecentProduct".equals(cookie.getName())){
                        recentview = cookie.getValue();
                        break;
                    }
                }
            }
            if(recentview != null){
                recentview = URLDecoder.decode(recentview, "UTF-8");
                String[] splits = recentview.split(",");
                for(String p : splits){
                    html += (product.getValueById(Integer.parseInt(p)) + "<br/>");
                }
            }
            html+=("</body>");
            html+=("</html>");
            response.getWriter().write(html);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    DetailServlet

    package com.http.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.URLEncoder;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.Stack;
    import java.net.URLEncoder;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.common.product.Product;
    import com.common.tool.MySet;
    
    @SuppressWarnings("unused")
    public class DetailServlet extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public DetailServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            int id = Integer.parseInt(request.getParameter("id"));
            System.out.println(id);
            Product product = new Product().getValueById(id);
            String html = "";
            html+=("<html>");
            html+=("<head>");
            html+=("<meta charset='utf-8'/>");
            html+=("<title>");
            html+=("商品信息");
            html+=("</title>");
            html+=("</head>");
            html+=("<body>");
            html+=("<table align='center' border='1'>");
            
            html+=("<tr>");
            html+=("<th>");
            html+=("编号");
            html+=("</th>");
            html+=("<td>");
            html+=(id);
            html+=("</td>");
            html+=("</tr>");
            
            html+=("<tr>");
            html+=("<th>");
            html+=("商品名称");
            html+=("</th>");
            html+=("<td>");
            html+=(product.getName());
            html+=("</td>");
            html+=("</tr>");
            
            html+=("<tr>");
            html+=("<th>");
            html+=("商品型号");
            html+=("</th>");
            html+=("<td>");
            html+=(product.getType());
            html+=("</td>");
            html+=("</tr>");
            
            html+=("<tr>");
            html+=("<th>");
            html+=("商品价格");
            html+=("</th>");
            html+=("<td>");
            html+=(product.getPrice());
            html+=("</td>");
            html+=("</tr>");
            
            html+=("</body>");
            html+=("</html>");
            Cookie acookie = null;
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if("RecentProduct".equals(cookie.getName())){
                        acookie = cookie;
                        break;
                    }
                }
            }
            System.out.println(product.getName());
            if(acookie == null){
                acookie = new Cookie("RecentProduct", product.getId()+"");
                response.addCookie(acookie);
            }else{
                String[] splits = acookie.getValue().split(",");
                HashSet<MySet> set = new HashSet<MySet>();
                set.add(new MySet(0, product.getId()+""));
                for(int i = 0, j = 0; i < splits.length;i++){
                    if((product.getId()+"").equals(splits[i]))
                        continue;
                    j++;
                    set.add(new MySet(j, splits[i]));
                }
                
                String value = "";
                Iterator<MySet> iterator = set.iterator();
                for(int i = 0; iterator.hasNext()&& i < 3; i++){
                    MySet mySet = iterator.next();
                    value += (mySet.getName() + ",");
                }
                acookie = new Cookie("RecentProduct", value);
                response.addCookie(acookie);
            }
            response.getWriter().write(html);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }


    4 Session技术

    4.1 引入

    Cookie的局限:

    1Cookie只能存字符串类型。不能保存对象

    2)只能存非中文。

    31Cookie的容量不超过4KB

    如果要保存非字符串,超过4kb内容,只能使用session技术!!!

    Session特点:

    会话数据保存在服务器端。(内存中)

    4.2 Session技术核心

    HttpSession类:用于保存会话数据

    1)创建或得到session对象

    HttpSession getSession()  

    HttpSession getSession(boolean create)  

    2)设置session对象

    void setMaxInactiveInterval(int interval)   设置session的有效时间

    void invalidate()      销毁session对象

    java.lang.String getId()   得到session编号

    3)保存会话数据到session对象

    void setAttribute(java.lang.String name, java.lang.Object value)   保存数据

    java.lang.Object getAttribute(java.lang.String name)   获取数据

    void removeAttribute(java.lang.String name) 清除数据

    4.3 Session原理

    问题: 服务器能够识别不同的浏览者!!!

    现象:

       前提: 在哪个session域对象保存数据,就必须从哪个域对象取出!!!!

    浏览器1(s1分配一个唯一的标记:s001,s001发送给浏览器)

    1)创建session对象,保存会话数据

    HttpSession session = request.getSession();   --保存会话数据 s1

    浏览器1 的新窗口(带着s001的标记到服务器查询,s001->s1,返回s1

    1)得到session对象的会话数据

        HttpSession session = request.getSession();   --可以取出  s1

    新的浏览器1(没有带s001,不能返回s1)

    1)得到session对象的会话数据

        HttpSession session = request.getSession();   --不可以取出  s2

    浏览器2(没有带s001,不能返回s1)

    1)得到session对象的会话数据

        HttpSession session = request.getSession();  --不可以取出  s3

    代码解读:HttpSession session = request.getSession();

    1)第一次访问创建session对象,给session对象分配一个唯一的ID,叫JSESSIONID

    new HttpSession();

    2)把JSESSIONID作为Cookie的值发送给浏览器保存

    Cookie cookie = new Cookie("JSESSIONID", sessionID);

    response.addCookie(cookie);

    3)第二次访问的时候,浏览器带着JSESSIONIDcookie访问服务器

    4)服务器得到JSESSIONID,在服务器的内存中搜索是否存放对应编号的session对象。

    if(找到){

    return map.get(sessionID);

    }

    Map<String,HttpSession>]

    <"s001", s1>

    <"s001,"s2>

    5)如果找到对应编号的session对象,直接返回该对象

    6)如果找不到对应编号的session对象,创建新的session对象,继续走1的流程

    结论:通过JSESSIONcookie值在服务器找session对象!!!!!

    4.4 Sesson细节

    1java.lang.String getId()   得到session编号

    2)两个getSession方法:

    getSession(true) / getSession()  : 创建或得到session对象。没有匹配的session编号,自动创 建新的session对象。

    getSession(false):              得到session对象。没有匹配的session编号,返回null

    3void setMaxInactiveInterval(int interval)   设置session的有效时间

    session对象销毁时间:

    3.1 默认情况30分服务器自动回收

    3.2 修改session回收时间

    3.3 全局修改session有效时间

    <!-- 修改session全局有效时间:分钟 -->

    <session-config>

    <session-timeout>1</session-timeout>

    </session-config>

    3.4.手动销毁session对象

    void invalidate()      销毁session对象

    4)如何避免浏览器的JSESSIONIDcookie随着浏览器关闭而丢失的问题

    /**

     * 手动发送一个硬盘保存的cookie给浏览器

     */

    Cookie c = new Cookie("JSESSIONID",session.getId());

    c.setMaxAge(60*60);

    response.addCookie(c);

    代码SessionDemo1

    package com.http.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.URLEncoder;
    
    import javax.servlet.ServletException;
    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;
    
    public class SessionDemo1 extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public SessionDemo1() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            HttpSession session = request.getSession();
            System.out.println("id = "+session.getId());
            session.setAttribute("name", "rose");
            session.setMaxInactiveInterval(60*60);
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60*60);
            response.addCookie(cookie);
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    SessionDemo2:

    package com.http.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class SessionDemo2 extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public SessionDemo2() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            HttpSession session = request.getSession(false);
            if(session != null){
                System.out.println(session.getAttribute("name"));
            }
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
            out.println("<HTML>");
            out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    This is ");
            out.print(this.getClass());
            out.println(", using the POST method");
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    DeleteSession

    package com.http.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class DeleteSession extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            HttpSession session = request.getSession(false);
            if(session != null){
                session.invalidate();
                System.out.println("销毁成功");
            }
        }
    
    }
  • 相关阅读:
    java实现第九届蓝桥杯最大乘积
    java实现第九届蓝桥杯最大乘积
    Anaconda入门使用指南
    Java安全——密钥那些事
    关于keyGenerator,KeyPairGenerator,SecretKeyFactory的解析
    @Transactional事务几点注意
    三种方式都是通过某种公开的算法将原始信息进行编码 /加密
    信息摘要算法 MessageDigestUtil
    Java使用RSA加密解密签名及校验
    java util
  • 原文地址:https://www.cnblogs.com/handsomecui/p/6117149.html
Copyright © 2011-2022 走看看