简体   繁体   中英

How to pass bean value to javascript in jsp?

I am trying to pass an int from a bean to a jsp page (using something like <%= TestBean.getNumber()%> ).

But when I am trying to pass it to javascript in the page, it's giving me error that says: " non-static method cannot be referenced in static context" . I am trying to form a loop in the script, something like:

    for (int i = 0; i < (<%= TestBean.getNumber()%>); i++) 
    {
    // 
    }

Anyone knows how to pass a bean value to javascript? Thanks.

Your bean name TestBean looks as your class name.

The compiler thinks you are trying to access a class method (an static method). If you are trying to call an instance method (non static), you need to define the name of the bean instance.

The convention is that classes start with uppercase names and instances use a lowercase name. Try declaring your bean instance following this rule (lowercase name).

For instance:

<html>
    <head>
        <script>
        <%
            class SampleBean {
                String _value;
                public String getValue () { return _value; }
                public void setValue (String value) { _value = value; }
            }
            SampleBean sb = new SampleBean();
            sb.setValue("Hello World!");
        %>
        v = "<%= sb.getValue() %>";
        </script>
    </head>
    <body>
        <a href="javascript:alert(v)">Click me!</a>
    </body>
</html>

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