JSF inputText and sessions in jsf managed bean

I would like to know how I can read the value of input text from a managed bean. I know that you can read this way, and it is very difficult.

<h:inputText id="username" value="#{mylogin.username}" required="true" />

But what if I say that I have a value like

 <h:inputText id="username" value="some_value" required="true" />

And I want to read this "some_value" in my managed bean. Is it possible?

Another question: is it possible to access session variables in a managed bean, or should I somehow pass them there?

+3
source share
3 answers

In the latter case, that is some_valuenot controlled by a bean, IMHO. However, you can read it. Do something like that

FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest request =
      (HttpServletRequest)ctx.getExternalContext().getRequest(); 
request.getParameter("username");

Similarly, regarding access to a session variable,

FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest request =
      (HttpServletRequest)ctx.getExternalContext().getSession(false); 
+2
<h:inputText id="username" value="#{mylogin.username}" required="true" />

, . , ? , harto , , ( ) .

<h:inputText id="username" value="some_value" required="true" />

, . ExternalContext API- bean :

FacesContext facesContext = FacesContext
    .getCurrentInstance();
ExternalContext extContext = facesContext
    .getExternalContext();
Map<String, String> params = extContext
    .getRequestParameterMap();

But, aside from violating the model-view-presenter contract, you can run into some practical problems. The parameter key may not be "username", but might be something like "j_id_jsp_115874224_691:username", depending on whether you make the component a child of any NamingContainer(like UIForm - see the prependId attribute) or if the view is namespaced. Hard-coding this value anywhere is probably a bad idea. You can read about the relationship between JSF component IDs and rendered HTML IDs here. If you want to use UIComponent.getClientId to generate the the key, you are back to component binding because you need to get a reference to the component.

- bean..?

. ExternalContext.getSessionMap.

+3

A common way to read the value of a component is to create a binding to the component in your managed bean file and read the value from it.

For example:

<h:inputText id="username" value="some_value" required="true"
    binding="#{mylogin.usernameField}" />

Then in a managed bean:

private UIInput usernameField;

public void setUsernameField(UIInput usernameField) { 
    this.usernameField = usernameField;
}
public UIInput getUsernameField() { 
    return usernameField; 
}

Finally, to access the field value:

Object value = usernameField.getValue();
+2
source

Source: https://habr.com/ru/post/1709005/


All Articles