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!!!!

1

3 Answers 3

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

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"));

3 Comments

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.
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.
Thanks for your quick response.
0

There are two ways to use java variable on jsp

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

Hope this is useful for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.