4.cookie session

Posted 重庆刘亦菲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4.cookie session相关的知识,希望对你有一定的参考价值。

jsp:
  jsp介绍:
    JSP全名为Java Server Pages,中文名叫java服务页面
    本质是一个servlet
    运行在服务器端的一个小程序,可以生成动态的内容
  jsp的组成:
    html+java代码+jsp的标签
  jsp文件的后缀名:jsp
  jsp的作用:
    将内容的生成和显示进行分离

    jsp文件生成的类文件存放路径:
      workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\work\Catalina\localhost\项目名字\org\apache\jsp
  jsp的原理:
    jsp的执行流程:
      1.服务器查找jsp.找到对象jsp文件
      2.将jsp文件转成java文件
      3.jvm会把java文件编译成class文件
      4.运行class文件,生成动态内容,返回服务器
      5.服务器进行封装,最后返回给浏览器
    若是字符开头的Jsp文件,字符_jsp.java文件 例如:hello.jsp==>hello_jsp.java
    若是数字开头的Jsp文件,_数字_jsp.java文件 例如:1.jsp==>_1_jsp.java
  jsp的脚本:
    <%...%>:java代码片段
      代码会在_jspService()方法中
    <%=...%>:脚本表达式的输出
      代码会在_jspService()方法中
      不能以;结尾
    <%!...%>:声明表达式
      声明的是全局的
  jsp的注释:
    1.html注释
      内容会编译,java原码中会有,页面上不体现
    2.java注释
      不会运行,也不会在页面上显示
    3.jsp注释:推荐使用
      <%--
        注释内容
      --%>
      html和原码中都不会出现

用jsp模拟登陆表单:

<%@page import="a.jsp.login.User"%>
<%@ 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>
    <form method="post" action="/javaee_day11/login">
        <table border="1px">
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"></td>
            </tr>
            <tr>
                <td colspan="2">
                    <%=(request.getAttribute("loginmsg")==null?"":request.getAttribute("loginmsg"))
                    
                    %>
                    
                </td>
            </tr>
        </table>
     </form>
</body>
</html>

创建userbean:

package a.jsp.login;

public class User {

    private Integer id;
    private String username;
    private String password;
    private String email;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public User() {
        super();
    }
    public User(Integer id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
    }
    
}

操作数据库:

package a.jsp.login;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import util.JDBCUtil;

public class UserOperation {

    public User login(String username, String password) {
        // 通过jdbc查询用户是否存在
        Connection conn=null;
        Statement st=null;
        ResultSet rs=null;
        
        try {
            conn=JDBCUtil.getConnection();
            String sql="select * from user where username=‘"+username+"‘ and password=‘"+password+"‘";
            st=conn.createStatement();
            rs=st.executeQuery(sql);
            if(rs.next()){
                return new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.closeResources(conn, st, rs);
        }
        
        return null;
    }

}

LoginServlet:

package a.jsp.login;

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

public class LoginServlet extends HttpServlet {

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

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("utf-8");
        //接收参数
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        
        //调用方法
        UserOperation uo=new UserOperation();
        User user=uo.login(username, password);
        
        //处理结果
        request.setAttribute("user", user);
        request.getRequestDispatcher("/show").forward(request, response);
    }
}

ShowServlet:

package a.jsp.login;

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;

public class ShowServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        
        User user=(User)request.getAttribute("user");
        if(user==null){
            //转发到login.jsp
            request.setAttribute("loginmsg", "用户名和密码不匹配");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            //成功则打印user
            response.getWriter().print(user);
        }
    }

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

 

会话技术:
  会话的介绍:
    从用户打开浏览器开始,访问不同的资源,直到浏览器关闭。我们认为这是一次会话。
  会话的作用:
    因为http是一个无状态的协议。
    会话技术可以保存用户在访问不同资源时产生的一些数据。
  例如:
    我们只需要登录一次
    我们的浏览记录
    购物车
  会话的分类:
    coookie:浏览器端的会话技术
    session:运行在服务器端的会话技术
cookie:
  浏览器端的会话技术
  由服务器产生,通过响应头传递给浏览器。
  浏览器再次访问的时候,通过一定的规定,携带不同的cookie
  cookie是Http协议指定的。
  cookie的常用方法:
    构造方法:
      Cookie c=new Cookie(key,value);
      例如:
        Cookie c=new Cookie("aa","11");
    返回给浏览器的方法:
      response.addCookie(c);
      例如:
        Set-Cookie:aa=11
        Set-Cookie:bb=22
    获取cookie的方法:
      Cookie[] request.getCookies():获取cookie
      String cookie.getName():获取cookie的名称
      String cookie.getValue():获取cookie的值

  执行流程:
    1.当浏览器第一次访问服务器的时候,创建Cookie,通过response将cookie添加到响应头中,返回给浏览器
      格式:
        Set-Cookie:aa=11
    2.当浏览器再次访问服务器的时候,通过一定的规则,在请求头中携带相应的cookie
      格式:
        Cookie:aa=11;bb=22
  cookie的持久化:
    常用方法:
      setMaxAge(int):设置cookie的最大生存时间,以秒为单位
      int的设置:
        int=0:立即干掉cookie,必须path一样
        int=-1:默认,浏览器关闭即失效

  注意:
    默认情况下,浏览器关闭,cookie就销毁了
    cookie不能跨浏览器
    cookie的路径:
      常用方法:
        setPath():
      注意:
        默认的写法: 以"/"开始,以"/"结束,中间内容是访问路径从项目名开始,到servlet的最后一个/结束
      例如:
        http://locahost:8080/javaee_day11/a/b/c/hello
        默认的路径为:/javaee_day11//a/b/c/

    路径的作用:
      在访问服务器的时候,具体携带哪些cookie
    结论:
      若访问的路径包含cookie设置好的路径,则携带
    如:
      Cookie c=new Cookie("lastTime",new Date().getTime()+"");
      c.setMaxAge(60*60);
      c.setPath("/javaee_day11/a/b/c");
      再次访问时不会有cookie

创建、添加cookie

public class HelloCookieServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie a=new Cookie("aa","11");
        Cookie b=new Cookie("bb","22");
        
        //将cookie添加到响应头中
        response.addCookie(a);
        response.addCookie(b);

    }

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

    }
}

 

案例:获取上次访问时间(两个servlet)

public class RemServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.设置编码
        response.setContentType("text/html;charset=utf-8");
        
        //1.创建cookie
        Cookie c=new Cookie("lastTime",new Date().getTime()+"");
        
        //持久化
        c.setMaxAge(60*60);
        
        //2.添加到响应头中
        response.addCookie(c);
        
        //3.提示信息
        response.getWriter().print("时间已记录");
    }

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

    }
}


public class ShowRemServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.设置编码
        response.setContentType("text/html;charset=utf-8");
        
        //1.获取Cookie
        Cookie[] cookies=request.getCookies();
        for (Cookie cookie : cookies) {
            if("lastTime".equals(cookie.getName())){
                //2.显示时间
                long value=Long.parseLong(cookie.getValue());
                response.getWriter().print("您上一次访问的时间为"+new Date(value).toLocaleString());
                return;
            }
        }
        response.getWriter().print("您是第一次访问");
        
    }

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

    }
}

案例:获取上次访问时间(一个servlet)

public class RemPlusServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.设置编码
        response.setContentType("text/html;charset=utf-8");
        
        //1.获取cookie
        Cookie[] cookies=request.getCookies();
        
        //2.判断cookie是否有指定的
        /*
         * 有的话,展示最后一次访问时间
         * 没有的话,展示第一次访问
         */
        Cookie c=findCookie("lastTime",cookies);
        if(c!=null){
            //有的话展示第一次
            response.getWriter().print("上一次访问时间:"+new Date(Long.parseLong(c.getValue())).toLocaleString());
        }else{
            //没有展示第一次访问
            response.getWriter().print("你第一次访问");
        }
        
        //3.添加一个cookie,将这次访问的时间存进去
        c=new Cookie("lastTime",new Date().getTime()+"");
        c.setMaxAge(60*60);
        response.addCookie(c);
    }

    private Cookie findCookie(String string, Cookie[] cookies) {
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(string.equals(cookie.getName())){
                    return cookie;
                }
            }
        }
        return null;
    }

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

    }
}

案例:查看图书访问记录

<%@ 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>
      <a href="/javaee_day11/book?id=0">书0</a>
      <a href="/javaee_day11/book?id=1">书1</a>
      <a href="/javaee_day11/book?id=2">书2</a>
      <a href="/javaee_day11/book?id=3">书3</a>
      <a href="/javaee_day11/book?id=4">书4</a>
      
      <a href="/javaee_day11/myhistory.jsp">浏览记录</a>
</body>
</html>
<%@page import="util.CookieUtil"%>
<%@ 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>
    <%
        Cookie cookie=CookieUtil.findCookie("ids", request.getCookies());
        if(cookie==null){
            out.print("暂无访问记录");
        }else{
            String[] value=cookie.getValue().split("-");
            for(String s:value){
                out.print("书籍"+s+"</br>");
            }
        }
        
    %>
    
    <a href="/javaee_day11/store.jsp">继续访问</a>
</body>
</html>
import javax.servlet.http.Cookie;

public class CookieUtil {
    /**
     * 获取指定名称的cookie
     */
    public static Cookie findCookie(String name,Cookie[] cookies){
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(name.equals(cookie.getName())){
                    return cookie;
                }
            }
        }
        return null;
    }
}


public class MyHistoryServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        
        String id=request.getParameter("id");
        
        /*
         * 获取cookie
         * 如果有cookie
         *     检查是否有ids
         *         有,不操作
         *         没有,添加 new Cookie("ids",id)
         * 没有cookie
         *     new Cookie("ids",id)
         */
        Cookie[] cookies=request.getCookies();
        Cookie cookie=CookieUtil.findCookie("ids", cookies);
        String ids=null;
        if(cookie!=null){ //cookie不为null
            if(!("ids".contains(cookie.getValue()))){ //cookie不含ids
                ids=cookie.getValue()+"-"+id; //
            }
        }else{ //cookie为Null
            ids=id;
        }
        
        cookie=new Cookie("ids",ids);
        
        //处理结果
        response.addCookie(cookie);
        PrintWriter w=response.getWriter();
        w.print("您查看的图书是图书"+id+"");
        w.print("<a href=‘/javaee_day11/myhistory.jsp‘>查看访问记录</a>&nbsp;");
        w.print("<a href=‘/javaee_day11/store.jsp‘>继续访问</a>");
    }

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

    }
}

 

session:
  session是运行在服务器端的会话技术。为每一个用户的浏览器分配一个独享的session,用来存放当前浏览器的数据,
  返回给浏览器一个id(jsessionid),每次访问页面的时候,会携带jsessionid。服务器拿到jsessionid,然后在
  session池中查找对应的session,拿过来给浏览器使用。
  session要依赖于cookie。若浏览器的cookie禁用了,必须重写url。
  session是一个域对象。
  常用的方法:
    xxxAttribute()
    注意:session是javaweb特有的,不同于cookie
  生命周期:
    从request.getSession()开始产生,通过cookie将此jsessionid返回给浏览器。
  销毁时机:
    1.session过期
      session默认过期时间为30分钟 <session-timeout>30</session-timeout>
        通过setMaxInActiveInterval(int interval):设置session的过期时间,单位也是秒
    2.服务器关闭
    3.主动关闭
      通过session.invalidate()手动的销毁session
  session的执行流程:
    1.浏览器发送请求
    2.服务器接受请求,查看浏览器中是否有jsessionid,若有,则拿jsessionid去session池中找
      若能找到,直接拿过来使用;若找不到,则创建一个session将jsessionid通过cookie返回给浏览器
    3.浏览器中没有jsessionid,创建一个session,将jsessionid返回给浏览器。
  session的常用方法:
    HttpSession request.getSession():返回一个session

 

案例:用session显示购物车中商品及数量

<%@ 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>
    玫瑰  <a href="/javaee_day11/cart?name=玫瑰">添加到购物车</a></br>
    
    钻戒  <a href="/javaee_day11/cart?name=钻戒">添加到购物车</a></br>
    
    衣服  <a href="/javaee_day11/cart?name=衣服">添加到购物车</a></br>
    <hr/>
    <a href="/javaee_day11/session/cart.jsp">查看购物车</a>
</body>
</html>
public class Add2CartServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.设置编码
        response.setContentType("text/html;charset=utf-8");
        
        
        //1.接收参数 
        String name=request.getParameter("name");
        name=new String(name.getBytes("iso8859-1"),"utf-8");
        //request.setCharacterEncoding("utf-8");  仅针对post请求
        
        //2.添加到购物车
        /*
         * 2.1 获取一个购物车  从session中   Map<> cart
         * 2.2判断cart是否为空
         *         若为空,new Map 然后将当前商品添加到map中
         *         若不为空,先判断购物车中是否存在该商品
         *             若存在,count++
         *            若不存在,count=1
         */            
         
        
        //session中, cart=map商品,键cart,值map<String,Integer>
        Map<String,Integer> cart=(Map<String, Integer>) request.getSession().getAttribute("cart");
        if(cart==null){ //购物车为空
            cart=new HashMap<String,Integer>();
            cart.put(name,1);
        }else{//购物车不为空
            Integer count=cart.get(name);
            if(count==null){ //该种商品数量为0
                //cart.put(name, 1);
                count=1;
            }else{
                //cart.put(name,count++);
                count++;
            }
            cart.put(name,count);
        }
        
        //3.购物车添加到session中
        request.getSession().setAttribute("cart", cart);
        
        //4.提示信息
        PrintWriter w=response.getWriter();
        w.println("已添加到购物车");
        //String path=request.getContextPath();
        //w.print("<a href=‘"+path+"/session/productList.jsp‘>继续逛逛</a>&nbsp;");
        w.print("<a href=‘/javaee_day11/session/productList.jsp‘>继续逛逛</a>");
        w.print("<a href=‘/javaee_day11/session/cart.jsp‘>查看购物车</a>&nbsp;");
        
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }
}
<%@page import="java.util.Map.Entry"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Set"%>
<%@page import="java.util.Map"%>
<%@ 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>
    <table>
        <tr>
            <th>商品名称</th>
            <th>商品数量</th>
        </tr>
        
    <%
        //获取购物车
        Map<String,Integer> cart=(Map<String,Integer>)request.getSession().getAttribute("cart");
        if(cart==null){
            out.print("<tr><td colspan=‘2‘>购物车暂无商品</td></tr>");
        }else{
            //遍历购物车
            Set<Map.Entry<String,Integer>> set=cart.entrySet();
            Iterator<Map.Entry<String,Integer>> it=set.iterator();
            while(it.hasNext()){
                Entry<String,Integer> entry=it.next();
                String name=entry.getKey();
                Integer value=entry.getValue();
                out.print("<tr><td>"+name);
                out.print("</td><td>"+value+"</td><tr>");
            }
        }
    %>
    </table> 
    
    <a href="/javaee_day11/session/productList.jsp">继续购物</a>
</body>
</html>

 

url重写(知道了解)
  禁用cookie的时候需要重写url
  常用方法:
    response.encodeRedirectURL(url)
      用于对sendRedirect方法后的url地址进行重写
    response.encodeURL(url)
      用于对表单action和超链接的url地址进行重写
  cookie中不支持中文

public class Demo1Servlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("username", "tom");
        
        String url=response.encodeUrl("/javaee_day11/demo2");
        System.out.println(url);
        
        response.getWriter().print("<a href=‘"+url+"‘>demo2</a>");
    }

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

    }
}



public class Demo2Servlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=(String) request.getSession().getAttribute("username");
        response.getWriter().print(username);
    }

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

    }
}

 

以上是关于4.cookie session的主要内容,如果未能解决你的问题,请参考以下文章

Cookie&Session

JavaWeb 笔记总结

第六阶段 cookie和session总结

Cookie/Session/Token对比

cookie和session的区别

Django Web开发-cookie与session