pass attribute from Java to JavaScript - java

In my Java Class I added a variable:
model.addAttribute("pageID", "dashboard");
Inside JSP I can easily call that variable with ${pageID}. But is there a way I can call that variable directly in JavaScript? I tried all other suggestion I found over the internet, such as simply writing var value = "${pageID}" but that doesn't work.
Any suggestions ?

Have u tried this?
var value = "<%= pageID %>";

Related

How do I retrieve data from jsp pageContext

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 :)

Interaction between JSP and External javascript files

I am newbie to external javascript files (*.js). Basically I have my JSP ready but my manager wants me to add graphics in it.
So I found some *.js files. But I don't know how to communicate between them and my JSP page.
I want to pass data from jsp to external .js file.
Is there any mechanism to do that?
For e.g:-
Demo.jsp
out.print(request.getAttribute("Name"));
Now I want use/pass/set above value to main.js file how to do that?
<script type="text/javascript">
var myJavascriptVariable = <%= request.getParameter("Name")%>;
//or .getAttribute("Name")
</script>
This could do the trick, it will make a global Variable which could be accessed in main.js. When you have GET Parameters you could also use only JS:
var paramarr = window.location.search.substr(1).split("&");
var params = {};
for (var i = 0; i < paramarr.length; i++) {
var tmparr = paramarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
or a bit shorter:
var params = {};
// parse URL's GET parameters and iterate over them
window.location.search.substr(1).split("&"),forEach(function(el) {
var kv = el.split('"'); // split into [ key, value ] array
params[kv[0]] = kv[1];
});
Now you can access the parameter in JS via:
params['name']
Personally I would use AJAX (e.g. with the help of JQuery) to get Data for my JavaScript files, you can look at that at http://api.jquery.com/category/ajax/shorthand-methods/ (2018 edit: kust use native ajax calls or whatever JS framework is hyped this week ;-) )
If you are using .js file you can't write jsp sriptlet in it.
If you need to call value in .js file there is one simple way.
Assign values to input elements in .jsp page.(If you are not using values in .jsp page assign values to hidden input elements)
Then include.js file in your .jsp page
get values as javasript or jquery methods.
Ex:-
value= document.getElementById("element_id").value
OR If you are using jquery you can get as
value = $("#element_id").val();
You can declare a global js variable and assign the value.
<% String myValue = (String)request.getAttribute("Name"); %>
var global1 ='<%= myValue %>';

Passing portletSession value from Java to Javascript

I want to pass a value from my Java class to Javascript. I have set the value in portletSession. I don't know how to get a value from portletSession into the Javascript.
Here is the code I have used to set the value in the portletSession.
PortletSession portletSession = request.getPortletSession();
portletSession.setAttribute("noExist", noExist);
How can I do that?
Don't use portletSession, use Cookie instead. You can access cookies from javascript using document.cookies
But there is another way: just print the variable into script block and javascript can read it.
var variableFromJSP = <% print variable here %>;
hope this help

Confused about jsp behaviour while setting value based on id

In my jsp on readyfunction i am setting value for some variables
$(document).ready(function() {
........////some code.......
var compCode=$('#companyCode').val();
........////some code.......
$("#countrySectorinMemInfo").val(countrySec);
........////some code.......
});
my controller is returning one value say ABC and i am accessing this value using ,
<input type="hidden" value="${ABC}" id="companyCode">
suppose , if my jsp has more than two fields having same id as "countrySectorinMemInfo"
then how " $("#countrySectorinMemInfo").val(countrySec);" will work......
can anybody explain me ...???
both vaues will get set or only last value will be set ...?????
Multiple elements with the same ID is illegal in HTML. The browser behaviour is unspecified. Give them a different ID. If you need a common selector, use name or class instead.
I agree with #BalusC
you should use class names instead of IDs. I think all of the JavaScript libraries have methods to get elements by class name.
The jQuery way:
// Get all elements with class 'myclass'
var nodes = $('.myclass');
The YUI 2.7.0 Selector way:
// Get all elements with class 'myclass'
var nodes = YAHOO.util.Selector.query('.myclass');
The YUI 2.7.0 getElementsByClass way:
// Get all elements with class 'myclass'
var nodes = YAHOO.util.Dom.getElementsByClassName('myclass');

setting a javascript variable to a struts property map value

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.

Categories

Resources