hello i need to output a java variable inside a javascript call inside a tag inside a jsp !
for example:
<% String param = "hello";%>
<dmf:checkbox name="checkbox"
onclick = "selectAll(<%=param%>)"
/>
the javascript generated is:
selectAll(<%=param%>),this); but I actually want something like
selectAllCheckBoxes(Hello),this);
That's not escaping. That's just printing a scriptlet variable as if it is a JavaScript variable.
Besides, your examples are confusing, they doesn't match each other and the Javascript code is syntactically invalid. I can at least tell that JavaScript string variables are to be surrounded by quotes. If you want to end up with
selectAllCheckBoxes('Hello', this);
where Hello should be obtained as a value of the scriptlet local name variable (the param is a reserved variable name, you shouldn't use it yourself), then you need to do
selectAllCheckBoxes('<%= name %>', this);
In the same way, if you want to end up with
onclick="selectAll('Hello')"
you need to do
onclick="selectAll('<%= name %>')"
That said, I strongly recommend you to stop using the old fashioned scriptlets which are been discouraged since more than a decade. JSP programmers were been recommended to use taglibs and EL only to make the JSP code more clean and robust and better maintainable. You can use taglibs such as JSTL to control the flow in the JSP page and you can use EL to access the "back-end" data. Your example can be replaced by:
<c:set var="name" value="Hello" />
...
selectAllCheckBoxes('${name}', this);
Generate the whole attribute value with a scriptlet, like this:
<dmf:checkbox name="checkbox"
onclick = "<%= "selectAll(" + param + ")" %>" />
maybe you are trying to achieve this?
var myVar = '<%= (String)request.getParameter("tab") %>';
loadtabs(myVar);
Related
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
The following line of java code is giving me null pageContext.getRequest().getParameter("id");
When I print it out in jsp page using <%=request.getAttribute("id")%> I am able to see the data stored inside.
Is there another way to retrieve the data from the jsp page and assign it to a java variable?
Yes you can do it. Place your code between <% %>
<%
String userID = request.getParameter("userid");
out.println(userID);
%>
If you want to avoid scriptlets you can use JSTL:
<c:set var="userId" value="${param.usedId}"/>
In JSP you can use internal java function
if do you want to pull a query parameter you simply have to write
<%request.getParameter("id") %>
if do you want to assign something like you want to put a data inside P tag you simply have to write
<p><%=request.getParameter("message")%></p>
in this case your java message will be inside P tag
and like javascript variable
<script>var id=<%=request.getParameter("id")%></script>
here you have assigned id (javascript variable) with query parameter pulled from native java function, id do you want to assign normal java variable inside jsp you have simply write
<% String message=request.getParameter("message")%>
Hope this help :)
I've got a variable from an object on my JSP page:
<%= ansokanInfo.getPSystem() %>
The value of the variable is NAT which is correct and I want to apply certain page elements for this value. How do I use a tag to know the case? I tried something like
<c:if test = "${ansokanInfo.getPSystem() == 'NAT'}">
process
</c:if>
But the above doesn't display anything. How should I do it? Or can I just as well use scriptlets i.e.
<% if (ansokanInfo.getPSystem().equals("NAT"){ %>
process
<% } %>
Thanks for any answer or comment.
Try:
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).
<c:if test="${ansokanInfo.pSystem eq 'NAT'}">
I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:
This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.
Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".
So in your case the JSTL code should look like the following, note the capital 'P':
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
You can use scriptlets, however, this is not the way to go. Nowdays inline scriplets or JAVA code in your JSP files is considered a bad habit.
You should read up on JSTL a bit more. If the ansokanInfo object is in your request or session scope, printing the object (toString() method) like this: ${ansokanInfo} can give you some base information. ${ansokanInfo.pSystem} should call the object getter method. If this all works, you can use this:
<c:if test="${ ansokanInfo.pSystem == 'NAT'}"> tataa </c:if>
basically I want to do the following.
var myvar = '<s:property value="myMap['mapKey'].mapObjectValue" />'
but that fails. I've tried several variations of quotes and can't quite get it to work correctly. any ideas?
I can do this:
var myVar = <s:property value="myMap['mapKey'].mapObjectValue" />;
but then the javascript variable isn't a string, so I can't use it as needed.
If your first attempt is failing, I'm guessing that the problem is in the Javascript parsing. You might want to try escaping the string for Javascript, using Apache Commons Lang for example:
var myvar = '<s:property value="#org.apache.commons.lang.StringEscapeUtils#escapeJavaScript(myMap['mapKey'].mapObjectValue)" />';
It should be working, as the tag will be rendered before Javascript gets interpreted. If javascript value isn't getting setted properly, maybe
<s:property value="myMap['mapKey'].mapObjectValue" />
isn't returning the correct value.
As #BalusC said, theres is no need to make javascript compile on your IDE.
So according to my JSP reference book, as well as every other reference I can find on the web, I'm supposed to be able to do something like:
<%# tag dynamic-attributes="dynamicAttributesVar" %>
and then when someone uses an attribute that I didn't define in an attribute directive, I should be able to access that attribute from the "dynamicAttributesVar" map:
<%= dynamicAttributesVar.get("someUnexpectedAttribute") %>
However, that doesn't work, at all; I just get a "dynamicAttributesVar cannot be resolved" error when I try.
Now, I did discover (by looking at the generated Java class for the tag) that I can "hack" a working dynamic attributes variable by doing:
<% Map dynamicAttributesVar = _jspx_dynamic_attrs; %>
Now, that hack doesn't work unless I also use the dynamic-attributes parameter on my tag directive, so it seems that the parameter is doing something.
But what I want to know is, how can I make it do what it does for every other JSP user out there?
Just trying to get a badge for answering a four year old question.
I have this problem as well and came across some help at O'Reilly to use JSTL instead of scriptlets.
The original poster could have used this code to get all keys/values:
<c:forEach items="${dynamicAttributesVar}" var="a">
${a.key}="${a.value}"
</c:forEach>
This would get a specific value:
<c:out value="${dynamicAttributesVar['someUnexpectedAttribute']}"/>
Isn't "dynamicAttributesVar" the name of the key in the page context that the dynamic attributes are put into? So you could do
<c:out value="${dynamicAttributesVar.someUnexpectedAttributes}"/>
or if you must use scriptlets:
Map dynamicAttributes = (Map) pageContext.getAttribute("dynamicAttributesVar")
(Disclaimer: I haven't tried it, I've just used dynamic attributes in tags with direct Java implementations... but it seems reasonable)