java - Request、Session 和 ServletContext 中属性的区别

标签 java jsp servlets web

<分区>

我无法理解这 3 种设置属性的方式之间的区别:

// String as attribute of request
req.setAttribute("name", "Sluggo");

// Integer as attribute of session
req.getSession().setAttribute("age", 10);

// Date as attribute of context
getServletContext().setAttribute("today", new Date());
  1. 有什么区别?
  2. 什么时候应该使用它们?

最佳答案

A ServletContext attribute is an object bound into a context through the ServletContext.setAttribute() method and which is available to ALL Servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications.

Session attributes are bound to a Session, as a mean to provide state to a set of related HTTP requests. Session attributes are available ONLY to those Servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the Session implementing the HttpSessionBindingListener interface.

Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keeps being dispatched from Servlet to Servlet. They're used more as communication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters...) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy.

IN SUMMARY, we can say that:

  • Context attributes are meant for infra-structure, such as shared connection pools.
  • Session attributes are meant for contextual information, such as user identification.
  • Request attributes are meant for specific request info, such as query results.

来源:Servlets Interview Questions by Krishna Srinivasan @ javabeat.net

关于java - Request、Session 和 ServletContext 中属性的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15398930/

相关文章:

java - 如果参数的值为字符串或数组,则验证 JSON 字符串

java - Hibernate getCurrentSession 与异步 servlet 的行为

java - 将 Spring 与 JSF2 集成

java - Jsp+Java 应用程序执行不工作

java - 在我的 jsp 页面上包含 jsp 文件时出错

java - 检查 List 是一种类型还是其他类型

java - 如何使用 Jquery 将多个值传递给 servlet

java - 大整数、平方根、Java 和 C : What does this line do?

java - jOOQ - 别名和引号错误

java - 如何在jsp中获取文本框中下拉选择的值