[英]@ManagedProperty on #{param} does not work in @ViewScoped
我的豆子有這個:
@ManagedBean
@ViewScoped
public class BookBean implements Serializable
{
@ManagedProperty(value = "#{param.id}") // does not work with @ViewScoped
private String id;
public void init()
{
id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id")
if (id != null) {
System.out.println("ID: " + id);
currentBook = bookService.find(id);
}
}
@PostConstruct
public void post()
{
// does not work with @ViewScoped
System.out.println("ID: " + id);
currentBook = bookService.find(id);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
目的地Facelet具有以下功能:
<f:metadata>
<f:viewParam name="id" value="#{bookBean.id}">
<f:event type="preRenderView" listener="#{bookBean.init}" />
</f:viewParam>
</f:metadata>
通過測試,我注意到@ManagedProperty
和@PostConstruct
僅適用於@RequestScoped
bean。
對於@ViewScoped
bean,我發現我必須這樣做FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id")
才能獲取id
參數的值。
這是通過@ViewScoped
獲取請求參數值的唯一方法嗎?
有什么想法嗎?
視圖范圍比請求范圍寬。 @ManagedProperty
只能設置與托管bean范圍相比具有相同或更大范圍的屬性。
只需將<f:viewParam>
與<f:event>
。 您不應只將它們嵌套在一起。
<f:metadata>
<f:viewParam name="id" value="#{bookBean.id}" />
<f:event type="preRenderView" listener="#{bookBean.init}" />
</f:metadata>
同
@ManagedBean
@ViewScoped
public class BookBean implements Serializable {
private String id;
public void init() {
if (id != null) {
currentBook = bookService.find(id);
}
}
// ...
}
<f:viewParam>
將設置請求參數,而<f:event>
將在設置這些參數后執行偵聽器方法。
@PostConstruct
在視圖作用域的bean上也可以正常工作,但是它僅在bean構造並設置了所有依賴項注入(例如@ @ManagedProperty
,@ @EJB
,@ @Inject
, @Resource
等)后直接運行。 但是<f:viewParam>
之后會設置屬性,因此@PostConstruct
不可用。
這是在ViewScoped bean中獲取請求參數的另一種方法。 這就是#{param.device}在RequestScoped bean中得到的。 這樣做的優點是在表示層中不需要任何標簽。
private int deviceID;
public int getDeviceID() {
if (deviceID == 0) {
String s = FacesContext.getCurrentInstance().getExternalContext().
getRequestParameterMap().get("device");
try {
deviceID = Integer.parseInt(s);
} catch (NumberFormatException nfe) {
}
}
return deviceID;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.