2

私の豆にはこれがあります:

@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> 

テストを通じて、私はそれに気づき、Bean@ManagedProperty@PostConstructのみ動作することに気付きました。@RequestScoped

Bean の場合、パラメーターの値を取得する@ViewScopedにはこれを行う必要があることがわかりました。FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id")id

これは、リクエスト パラメータの値を取得する唯一の方法@ViewScopedですか?

何かご意見は?

4

2 に答える 2

6

ビューのスコープは、リクエストのスコープよりも広いです。は@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

于 2011-04-16T15:26:10.820 に答える
1

これは、ViewScopedBean内でリクエストパラメータを取得するための別のメソッドです。これは、#{param.device}がRequestScopedBeanで取得するものです。これには、プレゼンテーション層にタグを必要としないという利点があります。

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;
}
于 2011-05-16T16:29:08.623 に答える