将输入文本值传递给bean方法,而不将输入值绑定到bean属性

mem*_*und 37 jsf parameter-passing managed-bean

我可以将输入文本字段值传递给bean方法而不将值绑定到bean属性吗?

<h:inputText value="#{myBean.myProperty}" />
<h:commandButton value="Test" action="#{myBean.execute()} />
Run Code Online (Sandbox Code Playgroud)

我可以不进行临时保存#{myBean.myProperty}吗?

Bal*_*usC 51

将组件绑定UIInput到视图并用于UIInput#getValue()将其值作为方法参数传递.

<h:inputText binding="#{input1}" />
<h:commandButton value="Test" action="#{myBean.execute(input1.value)}" />
Run Code Online (Sandbox Code Playgroud)

public void execute(String value) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

注意,这种方式的值已经转换并验证了通常的JSF方式.

也可以看看:


Lui*_*oza 15

您可以通过获取Request并使用普通Java EE ServletRequest#getParameter来恢复表单的参数.使用此方法时,请记住设置组件的ID和名称:

<h:form id="myForm">
    <h:inputText id="txtProperty" /> <!-- no binding here -->
    <input type="text" id="txtAnotherProperty" name="txtAnotherProperty" />
    <h:commandButton value="Test" action="#{myBean.execute()} /> 
</h:form>
Run Code Online (Sandbox Code Playgroud)

托管Bean:

@ManagedBean
@RequestScoped
public class MyBean {
    public void execute() {
        HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String txtProperty = request.getParameter("myForm:txtProperty");
        //note the difference when getting the parameter
        String txtAnotherProperty= request.getParameter("txtAnotherProperty");
        //use the value in txtProperty as you want...
        //Note: don't use System.out.println in production, use a logger instead
        System.out.println(txtProperty);
        System.out.println(txtAnotherProperty);
    }
}
Run Code Online (Sandbox Code Playgroud)

另一个有更多信息的帖子: