- 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)
- 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)
- Is this a JSP (Java Server Pages) web application? – mellamokb Commented Feb 28, 2013 at 7:00
- yes.. first i need to read the CONNECTION_DBNAME value from java to javascript. then from javascript to jsp page. – Rachel Commented Feb 28, 2013 at 7:01
5 Answers
Reset to default 7 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.
<script>
<%
String dbname=(String)session.getAttribute("CONNECTION_DBNAME");
%>
</script>
this code is usefull to you..
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.
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();
You cannot access variables in the session from the client. You could provide an Ajax call for the client to dynamically retrieve the value, or leave the value set in a script block.
JSF:
<script>var dbName = "#{myBean.value}";</script>
(Literally from session, the key is the quotes need to be there if it's a string):
<script>var dbName = "#{session.getAttribute('CONNECTION_DBNAME')}";</script>
However, you should reconsider before going in this direction because it makes little sense to give JavaScript access to your database through such a mechanism. Unless your database is publicly exposed, then you appear to be down the path of exposing your database connection details, which the client should not need or have. Your server/page should serve as a relay to get this information.
Now, if this is an admin console, then you probably still don't want it in JavaScript, but displaying the settings is acceptable. Regardless, you probably don't need them in the Session unless the connection details are user specific.