【Servlet】session保存作用域
session保存作用域:一次会话范围都有效
Java的服务器端,有一块内存专门存储在session保存作用域的数据。
session保存作用域是和具体的某一个session对应的。
常用API:
- void session.setAttribute(k, v)
- Object session.getAttrivute(k) —> 返回的是Object类型的
- void removeAttribute(k)
代码示例
Demo04Servlet.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
// 演示从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
<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>
原文地址:https://blog.csdn.net/qq_39921135/article/details/137270019
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!