使用getter和setter的优点是什么 - 只能获取和设置 - 而不是简单地使用公共字段来存储这些变量?
如果getter和setter做的不仅仅是简单的get/set,我可以非常快地解决这个问题,但我并不是100%清楚如何:
public String foo;
Run Code Online (Sandbox Code Playgroud)
更糟糕的是:
private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Run Code Online (Sandbox Code Playgroud)
而前者需要很少的样板代码.
我注意到有不同的bean范围,如:
@RequestScoped
@ViewScoped
@FlowScoped
@SessionScoped
@ApplicationScoped
Run Code Online (Sandbox Code Playgroud)
每个人的目的是什么?如何为我的bean选择合适的范围?
假设我像这样指定一个outputText组件:
<h:outputText value="#{ManagedBean.someProperty}"/>
Run Code Online (Sandbox Code Playgroud)
如果我在someProperty调用getter for时打印一条日志消息并加载页面,那么注意每个请求多次调用getter是很容易的(在我的情况下发生了两次或三次):
DEBUG 2010-01-18 23:31:40,104 (ManagedBean.java:13) - Getting some property
DEBUG 2010-01-18 23:31:40,104 (ManagedBean.java:13) - Getting some property
Run Code Online (Sandbox Code Playgroud)
如果someProperty计算的值很昂贵,这可能是一个问题.
我用Google搜索了一下,认为这是一个已知问题.一个解决方法是包括一个检查,看看它是否已经计算过:
private String someProperty;
public String getSomeProperty() {
if (this.someProperty == null) {
this.someProperty = this.calculatePropertyValue();
}
return this.someProperty;
}
Run Code Online (Sandbox Code Playgroud)
这个问题的主要问题是你得到大量的样板代码,更不用说你可能不需要的私有变量了.
这种方法有哪些替代方案?没有那么多不必要的代码,有没有办法实现这一目标?有没有办法阻止JSF以这种方式行事?
感谢您的输入!
我在welcome.jsp上有这个
<c:set var="pgTitle" value="Welcome"/>
<jsp:include page="/jsp/inc/head.jsp" />
Run Code Online (Sandbox Code Playgroud)
这在head.jsp中:
<title>Site Name - ${pgTitle}</title>
Run Code Online (Sandbox Code Playgroud)
但变量是空白的,输出仅仅是
Site Name -
Run Code Online (Sandbox Code Playgroud)
我看过很多文章,我无法弄清问题是什么.如果我${pgTitle}在同一个welcome.jsp中的其他地方回显,那么它输出正常.
我在两个页面上都包含了核心标记库.
el ×2
getter ×2
java ×2
jsf ×2
abstraction ×1
jsf-2 ×1
jsp ×1
jstl ×1
managed-bean ×1
oop ×1
performance ×1
scope ×1
setter ×1