This question already has an answer here:
这个问题在这里已有答案:
- How do servlets work? Instantiation, sessions, shared variables and multithreading 7 answers
servlet如何工作?实例化,会话,共享变量和多线程7个答案
Was going through some Java Servlets code.
正在浏览一些Java Servlets代码。
I found attributes set and retrieved in 3 different ways.
我找到了以3种不同方式设置和检索的属性。
req.getSession().setAttribute("var1","value1");
req.setAttribute("var2", "value2");
getServletContext().setAttribute("var3", "value3");
req
is a variable of type HttpServletRequest
I am a little confused as to what is the difference between the three?
req是HttpServletRequest类型的变量我有点困惑,三者之间有什么区别?
2 个解决方案
#1
2
req.getSession().setAttribute("var1","value1");
- Is a Session Attribute.
。req.getSession()的setAttribute( “VAR1”, “值1”); - 是会话属性。
req.setAttribute("var2", "value2");
- Is a Request Attribute.
req.setAttribute(“var2”,“value2”); - 是请求属性。
getServletContext().setAttribute("var3", "value3");
- Is a Servlet Context Level (an Application) Attribute.
getServletContext()。setAttribute(“var3”,“value3”); - 是Servlet上下文级别(应用程序)属性。
#2
1
The first one is a session attribute, the second one is a request attribute and the third one is an attribute belonging to the ServletContext
.
第一个是会话属性,第二个是请求属性,第三个是属于ServletContext的属性。
If you don't know what the session is and how it differs from the request, you should be studying how HTTP works.
如果您不知道会话是什么以及它与请求的不同之处,您应该研究HTTP的工作原理。
The ServletContext
is a separate place for the server to keep certain information. You'd more often be getting the attributes from there, rather than setting them.
ServletContext是服务器保存某些信息的独立位置。您经常从那里获取属性,而不是设置它们。
#1
2
req.getSession().setAttribute("var1","value1");
- Is a Session Attribute.
。req.getSession()的setAttribute( “VAR1”, “值1”); - 是会话属性。
req.setAttribute("var2", "value2");
- Is a Request Attribute.
req.setAttribute(“var2”,“value2”); - 是请求属性。
getServletContext().setAttribute("var3", "value3");
- Is a Servlet Context Level (an Application) Attribute.
getServletContext()。setAttribute(“var3”,“value3”); - 是Servlet上下文级别(应用程序)属性。
#2
1
The first one is a session attribute, the second one is a request attribute and the third one is an attribute belonging to the ServletContext
.
第一个是会话属性,第二个是请求属性,第三个是属于ServletContext的属性。
If you don't know what the session is and how it differs from the request, you should be studying how HTTP works.
如果您不知道会话是什么以及它与请求的不同之处,您应该研究HTTP的工作原理。
The ServletContext
is a separate place for the server to keep certain information. You'd more often be getting the attributes from there, rather than setting them.
ServletContext是服务器保存某些信息的独立位置。您经常从那里获取属性,而不是设置它们。