Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript code to read java variable value

  • I have a session variable in java file.(TestConnection.java)

session.setAttribute("CONNECTION_DBNAME", dbName);

  • How to read CONNECTION_DBNAME value into javascript file.(utility.js)
like image 802
Rachel Avatar asked Feb 28 '13 06:02

Rachel


People also ask

How do I get the value of a variable in JavaScript?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!

How Pass value from class to JavaScript in Java?

Since JS code runs on the user's browser and Java runs on your server, the only way to pass data from Javascript to Java is by doing an Ajax call. On your server, you need a API endpoint which accepts requests, then after receiving the desired data, you can handle it on your Java program.

Can Java interact with JavaScript?

LiveConnect is a technique that allows Java and JavaScript to communicate with each other. It allows your Java class to call JavaScript methods and access the JavaScript environment. JavaScript can also access Java objects and invoke methods on them.


4 Answers

 First access the variable in scriptlet.

 <% 
    String param= (String)session.getAttribute("CONNECTION_DBNAME");
 %>

Then use like this.

  <script>
  var X = '<%=param%>';
  </script>

then you can access the name using x.

like image 103
PSR Avatar answered Sep 22 '22 13:09

PSR


    <script>
<%
    String dbname=(String)session.getAttribute("CONNECTION_DBNAME");
%>  
  </script>

this code is usefull to you..

like image 32
suresh manda Avatar answered Sep 19 '22 13:09

suresh manda


You can use hidden element in JSP to get the value from session like:- <textarea id="txtData" style.display='none'><%=session.getAttribute("CONNECTION_DBNAME") %></textarea>

afterwards you can get the value in your javascript by var dbConnName=document.getElementById("txtData").value;

and you are done.

like image 38
Ars Avatar answered Sep 19 '22 13:09

Ars


Scriptlets were OUTLAWED more than a decade ago!

A better way... in jsp, include the values in a hidden div:

<div id="javaValues" style="display: none;">
    <div id="employee">${employee}</div>
    <div id="dept">${dept}</div>
</div>

Use <div>'s rather than <input type="hidden">, since they will not interfere with your form-postings.

In javascript (assuming jQuery) you can then access the values, for example:

    var employee = $("#employee").html().trim();
    var dept = $("#dept").html().trim();
like image 37
Rop Avatar answered Sep 21 '22 13:09

Rop