简体   繁体   中英

how to access two different java entities as parameters in backing bean method

Mojarra 2.1.5 / Java

I have two entities : ie

class Primary { String name; String age }
class Second { String dept; String hour }
...

In my managed bean I developed a function to generate PDF regarding my front-end prime-faces radio button (Primary or Second).

If I select in radio button the Primary option, the managed bean method will fire generatePDF() and inside the generatePDF I have :

Primary pr = new Primary();
pr.name = xxxxx;
pr.age = yyyyy;
...
...

But how can I do to re-utilize the same method generatePDF for both entities (Primary and Second ? I need to access both entity properties regarding my radio selection.

I need to instantiate the entities dynamically (Or I instantiate Primary or I intantiaty Second at a time)

What about do something like this.

interface Pdfeable{  String writeToPDF();}
class Primary implements Pdfeable { String name; String age }
class Second impleaments Pdfeable { String dept; String hour }

Just override with the statements you want to send data to the PDF.

class Primary implements Pdfeable {
   String name; String age;
   public String writeToPDF(){
      return getName() +  "" + getAge();
   }
}

And write your code using the interface definition not concrete classes.

Assuming as per your question you need one class instantiation at a time as per radio button selection ,I would suggest you should create a valueChangeListener to your radio button.I have hardcoded the values of radio selectItem you can use any way either by bean-binding or hardcoded.

<h:selectOneRadio value="#{myBean.myRadioValue}" ... onclick="this.form.submit();" valueChangeListener="#{myBean.generatePDF}">
   <f:selectItem itemValue="Radio1" itemLabel="Primary-radio" />
    <f:selectItem itemValue="Radio2" itemLabel="Secondary-radio" />
   </h:selectOneRadio>

This code will submit the form where the radio button are contained when the onclick Javascript event is detected. On the server side, the action generatePDF will be executed. In this method, you can do your requiste as on Submit action getter and setter will be called and you can check which radio is selected by comparing using if () and do your stuff:

public void generatePDF(ValueChangeEvent evt) {
    if(getMyRadioValue.equals(Radio1)){
     Primary pr = new Primary();
pr.name = xxxxx;
pr.age = yyyyy;
}
else if(getMyRadioValue.equals(Radio2)){
 Secondary s = new Secondary();
s.dept = xxx;
s.hour = yyyy;}

... ...

}

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