SesssionServlet.java
package web;
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;
import javax.servlet.http.HttpSession;
/**
* Session技术学习
* 问题:
* 什么是Session?
* 一个用户的不同请求的数据共享怎么办?
* 原理:
* 用户第一次访问服务器,服务器会创建一个session对象给用户,并将session对象的JSESSIONID使用Cookie技术存储到用户的浏览器缓存中。
* 保证用户其它请求能够获取到同一个session对象。
* 特点:
* 存储在服务器端
* 服务器进行创建
* 依赖Cookie技术实现
* 一次会话
* session最大保存时间结束
* 作用:
* 解决了一个用户不同请求数据共享问题
* 使用:
* 创建Session对象/获取Session对象(通过获取sesssion标识符)
* HttpSession session = request.getSession();
* 设置:
* //最大非活动时间
* session.setMaxInactiveInterval(10);
* //强制失效
session.invalidate();
* Session的存取:
* session.setAttribute("uid", "123456");
session.getAttribute("uid");
* web.xml设置失效时间
*<!-- session失效时间 单位-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
*/
@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession session = request.getSession();
//设置最大生命周期
//session.setMaxInactiveInterval(10);
session.setAttribute("uid", "123456");
session.getAttribute("uid");
String id = session.getId();
System.out.println("session:"+id);
}
}
LoginServlet.java
package web;
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;
import javax.servlet.http.HttpSession;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession session = request.getSession();
//强制失效
session.invalidate();
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SessionServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- session失效时间 单位-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
最后修改于 2021-09-14 11:51:38
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

