-2

I'm trying to print java string return values into script java . this is my method in java class

public static String getchamps (){ //Bdconnection class
    String str;
    {
        str = "date" ;
    }

    return str ;
}

the question is how can i have this code

<script type="text/javascript" >
    "date"
</script>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

2 Answers2

3

You should in this context look at JSF as a HTML code generator. You can use JSF tags/components and EL expressions to let it produce the desired HTML output. As JavaScript is as being a client side language technically part of HTML (not of JSF!), you can just do the same for JavaScript.

Once you fix that bad static method to really comply the Javabeans specification as below:

public String getChamps() {
    return "date";
}

Then you can just let JSF print it as if it's a JS variable as below:

<script>
    var champs = "#{bean.champs}";
</script>

To verify the result, just open the JSF page in webbrowser and do rightclick, View Source. You should see something similar to:

<script>
    var champs = "date";
</script>

Beware of JS-special characters in the string though! This would fail if the string contains e.g. a doublequote or even a newline. If that's the case, then you'd better escape it using an EL function as shown in this answer: Escape JavaScript in Expression Language.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • #{bean.champs} my class is import javax.faces.bean.ManagedBean; @ManagedBean public class Bdconnection { public String str = "date"; public String getchamps(){ return str ; } } i tried #{Bdconnection.str} but does'nt work – Trigui Moez Apr 17 '15 at 12:05
  • Just exactly follow the example in the answer. Your method name is still wrong and the way how you referenced the property in EL is still wrong. The answer shows the proper way. I'm not sure why you keep trying doing things the different way. – BalusC Apr 17 '15 at 12:14
  • If you're unable to elaborate "doesn't work" in developer's terms, I suggest to take a pause, put this all aside, and carefully go through a sane JSF book to properly grasp the basic concepts. Then, once you're finished and come back to this all, you'll surely quickly spot your mistake. – BalusC Apr 17 '15 at 12:39
  • it works finally thank you , in fact i had a problem in my bean ! thanks a lot – Trigui Moez Apr 17 '15 at 12:43
-2

Do this:

<h:inputText id="propertyId" value="#{Bdconnection.str}" />

and access in script

document.getElementById('propertyId').val();
Shayan Ghosh
  • 882
  • 6
  • 14