JSF表单值在提交时消失

时间:2014-12-04 00:40:09

标签: jsf java-ee javabeans

当我尝试提交表单时,输入值存在于validation-method中,但是在submit-method中。为什么在程序到达submit-function时输入属性为空?

输入:asdf


genres.xhtml

<h:form>
    <h:inputText 
        id="userGenre"
        value="#{genres.input}"
        validator="#{genres.validateLength}"
        required="true" size="3"
        />
    <h:commandButton 
        value="Add genre"
        action="#{genres.submit}" 
        />
    <h:message for="userGenre" />
</h:form>


Genres.java

@Named
@SessionScoped
public class Genres {

    static final Logger LOG = LoggerFactory.getLogger(Genres.class);

    private String input = "";

    public void validateLength(FacesContext context, UIComponent toValidate, Object value) {
        LOG.info("Validating");

        input = (String) value;
        LOG.info("name:"+input); // result: "name:asdf"

        int min = 3;
        int max = 15;
        int len = input.length();
        if (len < min || len > max) {
            ((UIInput) toValidate).setValid(false);
            FacesMessage message = new FacesMessage("Must be at least 3 and at most 15 characters.");
            context.addMessage(toValidate.getClientId(context), message);
            return;
        }
    }

    public void submit() {
        LOG.info("Submitting");
        LOG.info("name:"+input); // result: "name:"

        // process input
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

}


面向-config.xml中

<managed-bean>
    <managed-bean-name>genres</managed-bean-name>
    <managed-bean-class>no.krystah.Genres</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    <managed-property>
        <property-name>input</property-name>
        <property-class>java.lang.String</property-class>
        <value/>
    </managed-property>
</managed-bean>

1 个答案:

答案 0 :(得分:1)

#{genres.submit}尝试提交时,JSF会生成类型类的新实例,因此输入为空,但如果您使用 流派类顶部的@ManagedBean 注释我认为代码应该运行良好