簡體   English   中英

#{param}上的@ManagedProperty在@ViewScoped中不起作用

[英]@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM