Javascript code to read java variable value - java

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)

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.

Related

PHP's variable variables analog in JSTL

In PHP we can do the following with the help of Variable variables in PHP:
$privateVar = 'Hello!';
$publicVar = 'privateVar';
echo $$publicVar; // Hello!
Suppose we have the following chunk of Java code:
request.setAttribute("privateVar", "Hello!");
request.setAttribute("publicVar", "privateVar");
I've tried the following but an error occurs.
${${publicVar}}
Does anyone know how we can get value of privateVar via using only publicVar in JSP (JSTL)?
UPDATE 1:
I have a custom tag which allows to print a message if an object foo doesn't have a field bar.
I know I must catch exceptions in the case but I don't want to handle ones in JSP. I want to do it only in CustomTag file.
<%-- JSP file --%>
<ctf:tagName varName="foo.bar" />
<%-- CustomTag file --%>
<%# attribute name="varName" required="true" rtexprvalue="true"%>
<c:catch var="exception">
<c:set var="valX" value="${${varName}}" scope="page"/>
</c:catch>
<c:if test="${exception != null}">Can't find getter for the VAR in the OBJ.</c:if>
UPDATE 2:
JB Nizet gave me the answer and the following works well! :)
<c:set var="privateVar" value="Hello!" />
<c:set var="publicVar" value="privateVar" />
${pageScope[pageScope.publicVar]}
I don't think you can directly do this in the same way that you can in PHP. Instead you could change the attribute to use the value of the privateVar instead of the name, like this:
String privateVar = "Hello!";
request.setAttribute("privateVar", privateVar);
request.setAttribute("publicVar", privateVar);
This gives you access to the value under both names, which I think is the closest you'd get. No need to even put the attribute privateVar in the request if you are ultimately going to use publicVar on the JSP.
Ultimately you may want to rethink the design here as it doesn't really work in Java.
The basics:
That's not JSTL but Expression Language. And you should only use a single ${} evaluator. The code would be:
${publicVar}
More info:
StackOverflow Expression Language wiki
To your problem:
Expression Language doesn't allow that. You cannot have private attributes in any scope (page, request, session, application), so you can at most set the attribute twice with different names but the same value. But as you may note, this is useless.

Pass Value by Using Request.setAttribute

I am trying to get attribute of spanId and set Attribute by using request. Then I want to pass the output. Although the first input is has value, it still return me null.
Below are my codes. Help will be appreciate! :)
<input id="spanId" name="spanId">
<%
String spanId = request.getParameter("spanId");
request.setAttribute("spanId",spanId);
%>
<%= request.getParameter("spanId") %>">
Use the getAttribute method instead of getParameter() like
<%= request.getAttribute("spanId") %>">
Just think if you are setting an attribute to request object how you can get it? by using getAttribute.... String spanId = request.getAttribute("spanId").
Also request attribute has request scope (scope lasts only till 1 request).
More on this over here http://docs.oracle.com/javaee/1.4/api/javax/servlet/jsp/JspContext.html
Avoid using scripting elements in your JSP.. remember you are tightly coupling your presentation and business logic.

read parameters passed by one jsp to another

I want to read parameter passed by one JSP to another using HTTP POST method.
Following are my two JSP files.
One.jsp
<body>
<form action="Two.jsp" method="post">
<input type="text" value="test value" name="txtOne">
<input type="submit" value="Submit">
</form>
</body>
Two.jsp
<body>
<% response.getWriter().println(request.getParameter("txtOne")); %>
</body>
I can access the parameter in Two.jsp file using scriplet.
I want to avoid scriplet, so I am looking for JavaScript or jQuery solution.
So far I have searched and found JavaScript solution which only reads parameters sent using GET method(query string only).
Any suggestion will be appreciated.
Thanks in advance.
Solution:
I was able to get the value using JSTL:
${param.txtOne}
Try expression language - ${txtOne}, of if the method in one.jsp is GET instead of POST, you would be able to read URL in javascript and extract parameter value from there.
Yes you can get the value by use of JSTL
${param.txtOne}
Update
From EL info page
In EL there are several implicit objects available.
EL Scriptlet (out.print and null checks omitted!)
---------------------------------- ---------------------------------------------
${param.foo} request.getParameter("foo");
${paramValues.foo} request.getParameterValues("foo");
${header['user-agent']} request.getHeader("user-agent");
${pageContext.request.contextPath} request.getContextPath();
${cookie.somename} Too verbose (start with request.getCookies())
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
I want to avoid scriplet, so I am looking for JavaScript or jquery solution.
Simply you cannot.
request object can only accessible on server side, i.e in your JSP. You cannot access request or response object in client side that i.e javascript/jquery/whatever.
If you want access jsp value in javascript, try something like
var news=<%= request.getParameter("txtOne")) %>;
As a side note: Avoid scriplets and go for Expression language.
It is time for you to move to some MVC framework like struts than plain JSP. Then you can fill an ActionForm from parameters and use them on Two.jsp.

how to share constants between Java and Javascript

I have in my java classes static variables CONSTANT_1, CONSTANT_2...
What is the best way to share these constants with my javascript functions or if there is a JQuery plugin for this.
Till now the only solution I can think of, is an ajax call in the beginning, to send these static variables to the client.
Thanks
I dont know whether this the best way or not, but it works.
var constant1=<%=class.CONSTANT_1%>;
you can set this static variable in a hidden field, then you can access it by javascript using this hidden field
<input type="hidden" value="<your static variable>" id="staticVariable" />
<script type="text/javascript">
function getStaticField(){
return document.getElementById("staticVariable").value;
}
</script>
I have faced this problem before. what i did is simply i declared hidden input field that i can access on the server side and set it's value with whatever i want.
<input type="hidden" runat="server" id="hiddenInput" />
then using the programming language(I use c#):
hiddenInput.Value = ValueOnServerSide;
Then using jQuery i get the value of this input on the client side.
$("[id$='hiddenInput']").val();
There is Technology called 'DWR' (directwebremoting).
By using this we can access Java classes directly in Javascript.
Try this, it may helpful to you.
Refference Links:
http://directwebremoting.org/dwr/introduction/getting-started.html
http://directwebremoting.org/dwr/introduction/scripting-dwr.html
You can use AJAX calls to get the value of the constants if you dont want to keep reloading the page.
If you are fine with the value only updating on refresh you can do what Sainath has told, this way you are not making unnecessary AJAX calls:
var constant1=<%=class.CONSTANT_1%>;

How can I call setParameter in a request object?

This is probably due to my misunderstanding and incomplete information of JSP and JSTL. I have a web page where I have input elements such as
<input name="elementID" value="${param.elementID}"/>
When I am trying to save the form, I check for that elementID and other elements to conform to certain constraints "numeric, less than XXX". I show an error message if they don't. All the parameters are saved and user does not need to type it again after fixing the error.
After saved, when I am redirecting to the same page for the object to be edited, I am looking a way to set the parameter like request.setParameter("elementID",..) Is there a way to do this ? However the only thing I can find is request.setAttribute.
HTTP responses does not support passing parameters.
JSP/Servelets allows you to either use request.setAttribute or session.setAttribute for that purpose. Both methods are available when processing the page you're redirecting to, So basically, you got it right...
Also, from what you describe, you may want to check client-side validation: don't submit the form until you're validating it using client-side scripting (javascript)
After the servlet processes the form, (ie. saves the user input in the database), have the servlet forward (not redirect, because that would lose the request params) the request to the same jsp which contains the form. So there is no need to set the params since the servlet is just passing back the same request object.
The jsp which contains the form should have inputs similar to this:
<form>
...
<input type="text" value="${elementid}"/>
...
</form>
The syntax ${varname} is EL. So if the elementid already has a value, it that textfield will contain that value. Alternatively if you have not used EL and/or JSTL, you use scriptlets (but that is highly unadvisable, EL and/or JSTL should be the way):
<form>
...
<input type="text" value="<%= request.getParameter("elementid") %>"/>
...
</form>
I had to include <%# page isELIgnored="false"%> to my jsp to allow code like ${elementid} to work

Categories