Search code examples
jsfmanaged-bean

Passing text field values from jsf page to managed bean


I have a JSF form which calls a method of a managed bean when the action button is clicked. The method is successfully called, but now I would like to access the values entered in the form field from the bean. Here is my code.

The view:

<h:form class="form-horizontal" action= "#{hello_World.message}" method="post" id="formId">      
 <div class="control-group">
  <label class="control-label" for="inputEmail">First Name</label>
  <div class="controls">
  <h:inputText id="firstname" placeholder="First Name" value="#{submission.firstName> </h:inputText>
  </div> 

  <div class="control-group">
   <label class="control-Label">Address</label>
   <div class="controls">
   <input type="text" placeholder="Address" />
   </div>
   </div>
    <h:commandButton value="click" action="#{submission.submitted}"/>       
</h:form>

The model:

@ManagedBean(name="submission", eager=true)
public class MainClass {    
String firstName = "Pranbsh";
public MainClass(){
    System.out.println("Helloworld started from managed bean");
}
private String getFirstName(){
    return firstName;
}
public void submitted(){
    System.out.println("Bean executed");
    System.out.println("First name is ") ;      
  }
}

Solution

  • Use getter and setter to get the values from the xhtml like this

    JSF form

    <h:form class="form-horizontal" action= "#{hello_World.message}" method="post" id="formId">      
      <div class="control-group">
      <label class="control-label" for="inputEmail">First Name</label>
      <div class="controls">
      <h:inputText id="firstname" placeholder="First Name" value="#{submission.firstName> </h:inputText>
      </div> 
    
       <div class="control-group">
       <label class="control-Label">Address</label>
       <div class="controls">
       <input type="text" placeholder="Address" />
       </div>
       </div>
        <h:commandButton value="click" action="#{submission.submitted}"/>       
    </h:form>
    

    Managed Bean

      public class Form {
        String firstName ="Pranish";
    
        public String getFirstName(){
            return firstName;
        }
    
        public void setFirstName(String firstName){
            this.firstName = firstName;
        }
    
        public void submitted(){
            System.out.println("Bean executed");
            setFirstName(firstName);
            System.out.println("First Name : " + getFirstName());   
        }
    
    }