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

Posted

技术标签:

【中文标题】将输入文本值传递给 bean 方法,而不将输入值绑定到 bean 属性【英文标题】:Pass input text value to bean method without binding input value to bean property 【发布时间】:2012-08-10 03:11:57 【问题描述】:

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

<h:inputText value="#myBean.myProperty" />
<h:commandButton value="Test" action="#myBean.execute() />

我可以在不临时保存#myBean.myProperty 的情况下执行此操作吗?

【问题讨论】:

这样做你会完成什么(换句话说,你为什么想要)? 我会保存几个属性,这些属性仅用作没有实际输入参数的“解决方法”。 【参考方案1】:

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

<h:inputText binding="#input1" />
<h:commandButton value="Test" action="#myBean.execute(input1.value)" />

public void execute(String value) 
    // ...

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

另见:

How does the 'binding' attribute work in JSF? When and how should it be used? JSF component binding without bean property

【讨论】:

推荐什么方式?这个,还是托管 bean 中的附加属性? @Alexander:从技术上讲,这取决于模型。如果可以的话,使模型尽可能光滑。显然,如果答案对您有用,您可以这样做。但是,从功能上讲,这种方法可能会使在代码上跟踪您的启动者/维护者感到困惑,并可能将他/她引向错误的方向,以了解您究竟为什么这样做。所以,我会亲自添加一个很好的&lt;!-- comment --&gt;,解释为什么你没有声明一个单独的模型属性。 这个答案确实很好用。我只是想知道,因为我以前从未见过这个。谢谢,我会的。 是否可以通过这种方式编辑 inputText 按钮的值,然后将其传回 bean?【参考方案2】:

您可以通过获取请求并使用纯 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>

托管 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);
    

另一个提供更多信息的线程:

Get request parameter values in JSF

【讨论】:

如何从输入框中检索值,如果它在一个面板内,它本身在一个表单内,即
@AjaySharma 您的输入缺少名称。设置名称,然后按名称检索值 试过但不起作用。如果输入字段是直接到表单字段,它可以工作,但如果它在任何面板或任何其他标签内,它就不会 呃...你有没有检查生成的 html 以查看组件的名称?在 jsf 中,名称通常是父容器加上 : 加上组件的 id,这就是你缺少它的原因...... 感谢 Luiggi,但我尝试了所有选项。最后,我通过使用表单标签下方的隐藏输入标签做了一个解决方法。我可以通过使用 getRequest().getParameter("param_name") 来检索值

以上是关于将输入文本值传递给 bean 方法,而不将输入值绑定到 bean 属性的主要内容,如果未能解决你的问题,请参考以下文章

构造函数不将初始数组值传递给方法

如何使用 HAProxy 发送响应而不将请求传递给 Web 服务器

如何将一些信息传递给视图而不将其包含在 URL 中(django 新手)

如何使用 v-on:change 将输入文本传递给我的 vue 方法?

如何自动将用户信息传递给 Bot Framework 对话实例,而不将其作为显式消息发布在聊天窗口中?

如何将文本框中输入的值传递给 PartialViewResult?