初识session
什么是session?
- session是一种会话技术,用于保存共享的会话数据至服务器端
session和cookie的区别
- cookie:由服务器创建,保存在浏览器端
session:由服务器创建,保存在服务器端
session原理
- 浏览器访问服务器,服务器创建session对象和ID属性,session对象储存在服务器,ID属性带回浏览器(用cookie带回去),浏览器再次访问服务器,带着ID访问,服务器选择响应的session对象进行“服务”。
session的API
- 获取或者创建session:
request.getSession(boolean creat)
request.getSession()
获得session的ID属性:session.ID()
session域的应用:
共享数据、传递数据、一个存一个取—–域范围一次会话
setAttribute(String name.Object obj)存数据
Object getAttribute(String name)取数据
removeAttribute(String name)删除(清除)数据
上才艺
获取Session对象
HttpSession session=request.getSession();
存入数据(域的使用)
session.setAttribute("infor","http://www.adminlog.xyz");
完整代码
SessionServlet
package Session; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/SessionServlet") public class SessionServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); //获取Session对象 HttpSession session=request.getSession(); //设置保存ID属性的cookie的生存时长 //则在规定时间后刷新"http://localhost:8080/GetSessionServlet"之前显示的ID会消失(生存周期到此结束'60s') Cookie cookie=new Cookie("JSESSIONID", session.getId()); cookie. setMaxAge(60); out.print(session.getId()+"<br>"+"<hr />"); //存入数据 // 将网址存入infor session.setAttribute("infor","http://www.adminlog.xyz"); // out.println("ID为:"+session.getId()+"<br>"+"<hr />"+"3秒后跳转到GetSessionServlet服务器"); response.setHeader("Refresh","3;URL=/GetSessionServlet"); //重定向至GetServlet // response.sendRedirect("/GetSessionServlet"); } }
GetSessionServlet
package Session; 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; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/SessionServlet") public class SessionServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out=response.getWriter(); //获取Session对象 HttpSession session=request.getSession(); //存入数据 // 将网址存入infor session.setAttribute("infor","http://www.adminlog.xyz"); // out.println("ID为:"+session.getId()+"<br>"+"<hr />"+"3秒后跳转到GetSessionServlet服务器"); response.setHeader("Refresh","3;URL=/GetSessionServlet"); //重定向至GetServlet // response.sendRedirect("/GetSessionServlet"); } }