5

我在 JSF 2.2.7 和 Primefaces 5 中打开对话框时遇到问题。我有一个打开对话框的按钮,问题是每次单击按钮时都会执行 @PostConstruct 方法。为什么?

我只想调用@PostConstruct 1 次,但我不想将范围更改为 Session (使用 @SessionScope 注释它可以完美地工作)。

这是我的看法:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jstl/core"
    xmlns:p="http://primefaces.org/ui">

<h:head>

</h:head>
<h:body>
    <h:form id="f1">
        <p:dialog widgetVar="trainingDialog2" id="d1">
            <h:outputText value="#{userViewBean.errorMessage}" />
        </p:dialog>
        <br />

        <p:dataTable id="dt1" value="#{userViewBean.infoList}" var="item">
            <p:column>
                <p:commandButton id="btn" update=":f1:d1"
                    oncomplete="PF('trainingDialog2').show()"
                    styleClass="ui-icon ui-icon-calendar">
                    <f:setPropertyActionListener value="#{item.id}"
                        target="#{userViewBean.errorMessage}" />
                </p:commandButton>
            </p:column>
        </p:dataTable>
    </h:form>
</h:body>
</html>

这是我的豆子:

package pl.jrola.java.www.vigym.viewcontroller.beans.userview;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;

@ManagedBean(name = "userViewBean")
@ViewScoped
public class UserViewBean implements Serializable {

    private static final long serialVersionUID = 6994205182090669165L;

    private String errorMessage;

    private List<UserProfileInfoBean> infoList;

    public List<UserProfileInfoBean> getInfoList() {
        return infoList;
    }

    public void setInfoList(List<UserProfileInfoBean> infoList) {
        this.infoList = infoList;
    }


    public UserViewBean() {

    }

    @PostConstruct
    public void postConstruct() {
        this.infoList = new ArrayList<UserProfileInfoBean>();
        for (long i = 0; i < 3; i++) {
            this.infoList.add(new UserProfileInfoBean(i));
        }

    }


    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }


}
4

1 回答 1

7

您正在混合 JSF bean 和 CDI bean 的注释,有效地使 bean 成为 @RequestScoped,因为它是 @ManagedBean 的默认值。

如果您使用 JSF bean,请使用:

javax.faces.bean.ManagedBean;
javax.faces.bean.ViewScoped;

如果您想购买 CDI bean,请使用:

javax.inject.Named;
javax.faces.view.ViewScoped;

如果您的服务器支持 CDI,您应该选择 CDI bean。

在此处阅读有关默认范围的更多信息: JSF 2 应用程序中的默认托管 Bean 范围是什么?

于 2014-08-23T14:22:48.830 回答