JSP中,创建一个Bean 的时候,需要指定作用域
<jsp:useBean id="beanId" class="class.of.bean" scope="xxx" />
scope 取值范围有四个,从作用域大小来看,从大到小依次是:
application:
session:
request:
page:
许多初学者不容易理解的是request 和page 的区别
实际上,request 是通过 request.setAttribute/getAttribute 存取
而page 就可看成一个纯本地变量,出了当前 jsp文件,就不存在,当然对于<%@ include %> 中的页面也有效。
forward 后,request中的变量还是有效,而page的就无效了。
下面一段是在JSP中创建Bean时最终执行的源代码:
private void doSetAttribute(String name, Object o, int scope) {
if (o != null) {
switch (scope) {
case PAGE_SCOPE:
attributes.put(name, o); // HashMap<String, Object> attributes
break;
case REQUEST_SCOPE:
request.setAttribute(name, o); //ServletRequest request
break;
case SESSION_SCOPE:
if (session == null) {
throw new IllegalStateException(Localizer
.getMessage("jsp.error.page.noSession"));
}
session.setAttribute(name, o); //HttpSession session
break;
case APPLICATION_SCOPE:
context.setAttribute(name, o); //ServletContext context
break;
default:
throw new IllegalArgumentException("Invalid scope");
}
} else {
removeAttribute(name, scope);
}
}