session保存作用域:一次会话范围都有效
Java的服务器端,有一块内存专门存储在session保存作用域的数据。
session保存作用域是和具体的某一个session对应的。
常用API:
- void session.setAttribute(k, v)
- Object session.getAttrivute(k) ---> 返回的是Object类型的
- void removeAttribute(k)
代码示例
Demo04Servlet.java
java
// 演示向HttpSession保存数据
public class Demo04Servlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("uname", "lina");
}
}
Demo05Servlet.java
java
// 演示从HttpSession保存作用域中获取数据
public class Demo05Servlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 它获取到的是Object类型
Object unameObj = request.getSession().getAttribute("uname");
System.out.println(unameObj);
}
}
web.xml
xml
<servlet>
<servlet-name>Demo04Servlet</servlet-name>
<servlet-class>com.atguigu.servlets.Demo04Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo04Servlet</servlet-name>
<url-pattern>/demo04</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Demo05Servlet</servlet-name>
<servlet-class>com.atguigu.servlets.Demo05Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo05Servlet</servlet-name>
<url-pattern>/demo05</url-pattern>
<servlet-mapping>