简体   繁体   中英

JSF Passing dynamic UI data to server

I have this code below:

<h:inputText id="userName" />
...
<h:commandButton actionListener="..." action="...">
<f:param name="userInput" value="user" />
</h:commandButton>

Basically I want to get the value of inputText (submitted by client) and store it into the <f:param> tag's attribute, value . I want to do this so i can just access the username from the request parameters. Is there a way to do this? I know I can use beans to store the input value, but I am just wondering if I can store request values into the request parameter object.

There are some ways:

  1. Get it from the request parameter map yourself. As per standard HTML specification, the name attribute of the HTML input element represents the HTTP request parameter name. In JSF, the name of the HTML input element is the same as the component's client ID.

    So, given a

     <h:form id="form"> <h:inputText id="userName" ... /> 

    which generates a <input name="form:userName"> , you can obtain the submitted value as follows

     String userName = context.getExternalContext().getRequestParameterMap().get("form:userName"); 

  2. Get it from the component yourself by UIInput#getValue() . JSF has already performed the steps of applying the request values, converting/validating them and updating the model value. If you don't bind the value attribute of the input component to a bean property, then it sticks there in the component itself. You just have to access it. Components are by their client ID available in the component tree.

     UIInput userNameComponent = context.getViewRoot().findComponent("form:userName"); String userName = (String) userNameComponent.getValue(); 

  3. Bind the input component to the view and pass UIInput#getValue() as action method argument.

     <h:inputText binding="#{userName}" ... /> <h:commandButton ... action="#{bean.submit(userName.value)}" /> 

    with

     public void submit(String userName) { // ... } 

Needless to say that just binding the input value to the bean is much cleaner.

You don't need f:param . You can access submited text like this:

FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("generatedParameter");

Generated parameter name is not really as simple as userName in your case, because JSF prepand id of naming container of your component. The simplest is to inspect your generated HTML code and see what is the name of your input component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM