在JSP中,如果两个属性添加了相同的名称但是范围不同,会发生什么。当我尝试这段代码时,我得到了页面范围属性值为null,会话范围值是我存储的。
<% pageContext.setAttribute("kumar", "MCA", PageContext.PAGE_SCOPE);
pageContext.setAttribute("kumar", "BSc", PageContext.SESSION_SCOPE);
%>
答案 0 :(得分:1)
我测试了这段代码并找到了预期的结果。
<%
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方法的具体实现。 / p>
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");
}
}
答案 1 :(得分:0)
如果属性在同一范围内,则可以覆盖具有相同名称的属性。调用这些属性时可以看到区别如下:
attribute in page scope: <%=pageContext.getAttribute("kumar", PageContext.PAGE_SCOPE)%>
attribute in session scope: <%=pageContext.getAttribute("kumar", PageContext.SESSION_SCOPE)%>
again attribute in page scope: <%=pageContext.getAttribute("kumar")%>