gpt4 book ai didi

java - 可以覆盖或维护具有相同名称但不同范围的属性吗?

转载 作者:行者123 更新时间:2023-12-01 11:07:29 25 4
gpt4 key购买 nike

在 JSP 中,如果添加两个名称相同但范围不同的属性,会发生什么情况。当我尝试此代码时,我得到的页面范围属性值为空, session 范围值是我存储的。

   <%  pageContext.setAttribute("kumar", "MCA", PageContext.PAGE_SCOPE);
pageContext.setAttribute("kumar", "BSc", PageContext.SESSION_SCOPE);
%>

最佳答案

我测试了这段代码并发现了预期的结果。

<% 
pageContext.setAttribute("kumar", "MCA", PageContext.PAGE_SCOPE);
pageContext.setAttribute("kumar", "BSc", PageContext.SESSION_SCOPE);
pageContext.setAttribute("kumar", "Inter", PageContext.APPLICATION_SCOPE);
%>
attribute in page scope: <%=pageContext.getAttribute("kumar", PageContext.PAGE_SCOPE)%>
attribute in session scope: <%=pageContext.getAttribute("kumar", PageContext.SESSION_SCOPE)%>
again attribute in application scope: <%=pageContext.getAttribute("kumar",PageContext.APPLICATION_SCOPE)%>

输出

attribute in page scope: MCA 
attribute in session scope: BSc
again attribute in application scope: Inter

每个范围都不同。正如评论中已经指出的,在高级范围和低级范围中没有这样的覆盖。为了更好地理解,请参阅 org.apache.jasper.runtime.PageContextImpl 中 getAttribute 方法的具体实现

 private Object doGetAttribute(String name, int scope) {
switch (scope) {
case PAGE_SCOPE:
return attributes.get(name);

case REQUEST_SCOPE:
return request.getAttribute(name);

case SESSION_SCOPE:
if (session == null) {
throw new IllegalStateException(Localizer
.getMessage("jsp.error.page.noSession"));
}
return session.getAttribute(name);

case APPLICATION_SCOPE:
return context.getAttribute(name);

default:
throw new IllegalArgumentException("Invalid scope");
}
}

另请参阅

关于java - 可以覆盖或维护具有相同名称但不同范围的属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com