0

I am writing a JSP and have the Java code written in the <code> tags.

I would like to use a Java variable which is inside the <code> tag, inside the script tag.

Example:-

  <html>
    <head>
    var myJSVar = $(myJavaVariable)//Something like this and this doesn't work
    </head>
    <body>
    <pre>
    <code>
     String myJavaVariable = "Sample String";
    </code>
    .....

Thanks!!!!

user3649158
  • 63
  • 1
  • 9
  • 1
    Possible duplicate of [java variable in a jsp tag?](http://stackoverflow.com/questions/5121954/java-variable-in-a-jsp-tag) – Tony Apr 26 '16 at 09:58

3 Answers3

2

First you have to declare , <% String myJavaVariable = "Sample String"; %>

Then in script, var myJSVar = "<%=myJavaVariable%>";

Dominic Philip
  • 108
  • 2
  • 10
1

Its not possible to get java variable inside a script. you can set the values in to a HTML element using java after you have done that you can use <script> tag to access the values which is in HTML element

    <% String Name="myName"; %>
    <input type="text" name="Name" id="Name"  value="<%=Name%>" maxlength="50" />

using script tag to get the data in html element.

<script>              
    var name = document.getElementById('Name').value;
    <script>

<code> is not a tag used in HTML to write java code. so you cant do any coding inside a code tag anything you will write in there will be just interpreted on browser in the format of a code.

changed the answer according to your comments.example on getting values as a json and converting them to java objects

  String json = "{\"Name\":\"priyamal\",\"Mob\":\"077045\"}";
    ObjectMapper mapperobject = new ObjectMapper();
    Map<String, Object> javaobj = mapperobject.readValue(json, new TypeReference<Map<String,Object>>() { });
    out.println("MyName:" + javaobj.get("Name") + "Mobile:" + javaobj.get("Mob"));
Priyamal
  • 2,919
  • 2
  • 25
  • 52
  • Actually I have a Json object like jsonPrettyPrintString it will display the json data on browser. I need a tree structure of ui on browser but it's simply displaying plain json code. – user3649158 Apr 26 '16 at 11:03
  • first of all you should to know how to ask a question properly.you have never mention anything related to getting values from as a json string. wait i'll update my answer. – Priyamal Apr 26 '16 at 12:18
  • 1
    Thanks for your quick response. – user3649158 Apr 28 '16 at 10:29
0

There are two ways to use java variable on jsp

  1. ${message}
  2. <%String myVar="blabla";%>

Hope this is useful for you.

Sampada
  • 2,931
  • 7
  • 27
  • 39
ankit singh
  • 153
  • 1
  • 5