HttpSession

1、HttpSession

HttpSession是由javaweb提供的,用来会话跟踪的类。session是服务器端对象,保存在服务器端。HttpSession是Servlet三大域对象之一(request,session,application(ServletContext)),所以也有setAttribute(),getAttribute(),removeAttribute()方法,HttpSession底层依赖Cookie,或是URl重写。

会话:一个用户对服务器的多次连贯性请求,所谓连贯性请求,就是该用户多次请求,中间没有关闭浏览器。会话范围:某个用户从首次访问服务器开始,到该用户关闭浏览器结束。

服务器会为每个客户端创造一个session对象,session就好比客户端在服务器端的账户,他们被服务器保存到一个Map中,这个Map被称之为session缓存。

Servlet中得到session对象:HttpSession session = request.getsession();session是jsp内置对象,不用创建就可以使用

2、用户登录示例:(校验用户信息)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>登录</h1>
<%
    String uname = "" ;
    Cookie[] cs = request.getCookies() ;
    if(cs != null) {
        for(Cookie c : cs) {
            if("uname".equals(c.getName())) {
                uname = c.getValue(); //得到后给文本框赋初值
            }
        }
    }
    request.getCookies() ;
%>
<%
    String message = "" ;
    String msg = (String)request.getAttribute("msg");
    if(msg != null) {
        message = msg ;
    }
%>
<font><b><%=message %></b></font>
<form action="/ali_web/ALoginServlet" method="post">
    用户名:<input type="text" name="username" value="<%=uname %>" /><br/>
    密    码:<input type="password" name="password" /><br/>
    <input type="submit" value="登录" />
</form>
</body>
</html>

————————————————————

package com.demo.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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("/ALoginServlet")
public class ALoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username") ;
        @SuppressWarnings("unused")
        String password = request.getParameter("password") ;
        if(!"error".equalsIgnoreCase(username)) {
            //附加:把用户名保存到cookie中,发送给客户端浏览器,当再次打开login.jsp时,其会读取request中的cookie,把它显示到用户名文本框中
            Cookie cookie = new Cookie("uname",username) ; //创建Cookie
            cookie.setMaxAge(60*60*24); //设置cookie命长为一天
            response.addCookie(cookie); //保存cookie
            
            HttpSession session = request.getSession() ;
            session.setAttribute("username", username);
            response.sendRedirect("/ali_web/Session/suc1.jsp"); //使用响应重定向而不是请求转发因为此时属性已经保存到session中,重定向依然能获取到session中保存的属性
        }else {
            request.setAttribute("msg", "用户名或密码错误!"); //保存到request请求域而不是session因为request请求域保存时间短,用户重新登录时就不需要之前的msg了
            RequestDispatcher qr = request.getRequestDispatcher("/Session/login.jsp") ; //转发器
            qr.forward(request, response); //请求转发(此时request请求域中保存的属性不会丢)
        }
    }
}
——————————————————————

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>suc1</title>
</head>
<body>
<%
    //当用户直接访问登录成功页面导致username为null时执行
    String username = (String)session.getAttribute("username");
    if(username == null) {
        request.setAttribute("msq", "未登录") ;
        request.getRequestDispatcher("/Session/login.jsp").forward(request, response) ;
        return;
    }
%>
<h1>欢迎,<%=session.getAttribute("username") %></h1>
</body>
</html>

3、HttpSession原理

当用户第一次访问Servlet时,服务器端会给用户创建一个独立的Session,并且生成一个SessionID,这个SessionID在响应浏览器的时候会被装进cookie中,从而被保存到浏览器中。

当用户再一次访问Servlet时,请求中会携带着cookie中的SessionID去访问,服务器会根据这个SessionID去查看是否有对应的Session对象,有就拿出来使用;没有就创建一个Session(相当于用户第一次访问)。

获取Session 对象:

request.getSession(), request.getSession(boolean Create);第二个方法,当参数为false时,表示如果session缓存中不存在session,那么返回null,而不会创建session对象。

4、获取UUID(JSESSIONID即为32位字符串)

/**
 *  得到32位的UUID
 * 在java.util包中就有一个UUID类
 */
UUID uuid = UUID.randomUUID() ;
String str = uuid.toString() ;
str = str.replace("-","") ;
str = str.toUpperCase() ;

5、HttpSession中的其他方法:

获取sessionId:String getId()

获取最大时效:int getMaxInactiveInterval()默认session的最大不活动时间为30分钟,即session在30分钟内没有使用,服务器就会在session池中移除

使HttpSession 失效:void invalidate()

查看session是否为新:boolean isNew()

6、在web.xml中配置session的最大不活动时间

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

7、URL重写

服务器创建好了Session对象,但是由于浏览器禁止了Cookie的接收,那么服务器无法将创建好的Session的ID值以Set-Cookie的响应头方式发送给浏览器进行存储,那么在第二访问的时候也就不会懈怠SessionID,因此无法找到Session。

常用解决方法:

String encodeRedirectURL(String url)        ->给指定的重定向路径后添加Sessionid信息

String encodeURL(String url)                     -> 给普通的URL地址添加Sessionid信息

//首先查看cookie是否存在,如果不存在,在指定的url后添加JSESSIONID参数,如果cookie存在,就不添加

path = response.encodeURL("/day08/list");
response.sendRedirect(path);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值