1.session
session对象用来存储有关用户会话的所有信息,这些信息保存在服务器端。
常用方法:
1.setAttribute(String key,Object value) 以key/value的形式保存对象值,void类型
2.getAttribute(String key) 通过 key 获取对象值,Object类型
3.getId() 获取 session 对象的编号,String类型
4.invalidate() 设置session对象失效,void类型
5.getCreationTime() 获取创建时间戳,long类型
6.getLastAccessedTime() 获取最后一次访问时间,int类型
7.**getMaxInactiveInterval()**获取session过期时间,int类型
@WebServlet(name = "Demo_04ServletTest",urlPatterns = "/Demo_04ServletTest")
public class Demo_04ServletTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取session对象
HttpSession httpSession=req.getSession();
PrintWriter printWriter=resp.getWriter();
//获取session id
String id=httpSession.getId();
//打印id
printWriter.println("id:"+id);
//设置session参数
httpSession.setAttribute("sessionName","session");
//获取session参数
printWriter.println("sessionArg:"+httpSession.getAttribute("sessionArg"));
//获取session创建时间
long createTime=httpSession.getCreationTime();
//打印
printWriter.println("createTime:"+createTime);
//获取最后登录时间
long lastAccessedTime=httpSession.getLastAccessedTime();
//打印
printWriter.println("lastAccessedTime:"+lastAccessedTime);
}
}
运行如图
基于session的登陆验证:
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
</head>
<body>
<div>
<form action="Demo_01Servlet_Login"method="post">
账号: <input type="text"name="id"><br>
密码: <input type="password"name="password"><br>
<input type="submit"value="登录"><br>
</form>
</div>
</body>
<