How to transfer java array to javaScript array using jsp? - java

I have a list of strings on my server which I am trying to get to the client in the form of an array. The code I am attempting to use is the following:
Within the jsp I have a List<String> column
I am attempting the following code:
<%int j = 0; %>
for(var i = 0; i < <%=columns.size()%>; i++)
{
colArray[i] = "<%=columns.get(j++)%>";
}
This code simply returns the first element in the columns list for every element in the colArray.
I have also tried:
colArray = <%=columns.toArray()%>;
which does not work either.
I feel like I am making a little mistake somewhere and am just not seeing it. Is what I am trying to do possible in the way that I am attempting?
Thanks.

You're getting the JSP code that is executed on the server mixed up with the JavaScript code that's executed on the client. The snippet <%=columns.get(j++)%> is executed once, on the server, and the JavaScript loop around it is irrelevant at this point. When it arrives the the client, the loop's body just says colArray[i] = "first entry"; which of course puts the same string into every element of the array.
What you need to do instead is to have a loop execute on the server, like this:
<% for (int i=0; i<columns.size(); i++) { %>
colArray[<%= i %>] = "<%= columns.get(i) %>";
<% } %>
My JSP skills are rusty, and the syntax may be different, but I hope you get the idea.
Edit: As was pointed out in the comments, you need to be VERY careful about escaping anything in those Strings that could cause them to be interpreted as JavaScript code (most prominently quotation marks) - especially if they contain user-generated content. Otherwise you're leaving your app wide open to Cross-site scripting and Cross-site request forgery attacks.

Try using JSON (Javascript object notation) it'd be quite simple to encode the array and decode it on javascript
check it out here
http://www.json.org/java/index.html

Once the JavaScript reaches the client, the server code has stopped executing. The server code does not execute "in parallel" with the client code.
You have to build the entire JavaScript initialization in Java and send it, complete and executable, to the client:
<%
StringBuffer values = new StringBuffer();
for (int i = 0; i < columns.size(); ++i) {
if (values.length() > 0) {
values.append(',');
}
values.append('"').append(columns.get(i)).append('"');
}
%>
<script type="text/javascript">
var colArray = [ <%= values.toString() %> ];
</script>
That is just one way to do it, you can also build the output "on the fly" by embedding the server code inside the [ and ]. I used this example to try to demonstrate the separation between building the string that comprises the client-side JavaScript and outputting that to the browser.

Exp Language:
colArray = ${columns}

For me this solution has worked. First of all You should make a JSONArray and use it's toJSONString() method. This method converts the list to JSON text. The result of it is a JSON array.
<%
List<String> exampleList = new ArrayList<>();
exampleList.add("Apple");
exampleList.add("Orange");
exampleList.add("Lemon");
JSONArray fruitList = new JSONArray();
fruitList.addAll(exampleList);
%>
In your JSP page you should invoke the toJSONString() method of the list, and pass the JSON text to a JavaScript array.
<script type="text/javascript"> var fruitArray = <%= fruitList.toJSONString() %>;</script>
(Optionally You could make a simple getter method for the list. In case if you only instantiate the JAVA class - which has the list field - int the JSP page.)

The solutions posted above didn't work in my case, I needed an extra Javascript variable to do the transference:
var codesJS=new Array();
<% String[] codes=(String[])request.getAttribute("codes");
if(codes!=null){
for(int i=0; i<codes.length; i++){ %>
var code='<%= codes[i] %>'; //--> without this doesnt work
codesJS[<%= i %>]=code;
<%}
}%>

Related

When do (jsp) scriptlets run their (Java) code?

I was working through a null pointer exception on code like the following:
<%
SessionData session = getSessionData(request);
Webpage webPage = null;
if (session!= null) {
webPage = session.getWebPage();
}
%>
<script type="text/javascript">
//NullPointer happens here, webPage is null when the session is lost
<tags:ComboBox
comboBox="<%=webPage.getComboBox()%>" />
</script>
I was surprised when I could move the ending of if (session!=null to after the javascript, which seems to ignore that code when the session was null.
<%
SessionData session = getSessionData(request);
Webpage webPage = null;
if (session!= null) {
webPage = session.getWebPage();
//} move this to below
%>
<script type="text/javascript">
//NullPointer happens here, webPage is null when the session is lost
<tags:ComboBox
comboBox="<%=webPage.getComboBox()%>" />
</script>
<% } %> //moved to here
Does the scriptlet for the ComboBox tag, inside the brackets, no longer run? I would think it would still try to get the combobox off the webpage, and still end up getting a null pointer. Am I incorrect in thinking that scriptlets all get their values before the code is actually ran?
(just thought I'd mention, there is an included script which redirects the page if there is no session. I get a NullPointer with the first section of code, and correctly redirect with the second section)
A JSP is compiled to a servlet on-the-fly by the servlet container.
This compilation is actually simple kind of inversion:
TEXT1
<% java code %>
TEXT2
<%= java expression %>
TEXT3
That is compiled to:
out.print("TEXT1");
java code
out.print("TEXT2");
out.print(java expression);
out.print("TEXT3");
So when you say:
TEXT1
<% if (true) { %>
TEXT2
<% } %>
TEXT3
You get:
out.print("TEXT1");
if (true) {
out.print("TEXT2");
}
out.print("TEXT3");
The above examples are minified for clarity, e.g. newlines are ignored, the boilerplate servlet setup is not included, and the complexity of tag library execution is not covered.
In short, you are incorrect as to the order in which tag libraries and scriptlets are processed; the JSP compiler first identifies JSP directives, then resolves and renders tag library output, and then converts everything not in a scriptlet into a bunch of static strings written to the page, before stitching the resulting Java file together around the existing scriptlet code, looking something like this:
// start of class and _jspService method declaration omitted for brevity
out.write("<html>\n");
out.write("\t<head>\n");
out.write("\t<title>Example Static HTML</title>\n");
// comment inside a scriptlet block
int x = request.getParameter("x");
pageContext.setParameter("x", x);
out.write("\t</head>\n");
The problem here stems from the fact that Tag Libraries are resolved first, and the code which isolates and evaluates them doesn't care about either scriptlet blocks or the DOM. In your case, the <tags:ComboBox> tag just thinks the scriptlet is a regular string.
What you should be doing instead is exposing the value in your scriptlet to the accessible scope used by the tag library; in the case of JSTL, for example, you need to add it into the page context via pageContext.setAttribute("varName", value).
Check this answer for more details.

inline java makes causing javascript to not execute

I have some javascript
<script>
// some java code that doesn't matter right now
localStorage.setItem("myName", "Bob");
alert(localStorage.myName);
<script>
it works just fine (giving an alert message that says Bob). that's fine and dandy but what I really want is to pass a java variable to a javascript variable and have that print out instead.
But when I put these lines into it...
var hi5 = <%= "getMyName();" %>
localStorage.someName = hi5;
It quits. Any javascript before that works fine. but any javascript after it just doesn't show up.
now the <% %> tags might not be in the exact syntax but it doesn't really give me any errors
I'm sure I'm overlooking something but I'm not sure what it would be. What can I do?
Because look at the source code of the page that this line generates
var hi5 = <%= "getMyName();" %>
It would render something this
var hi5 = BOB
Do you have a variable BOB? No. You are missing the quotes which would make it a string.
var hi5 = "<%= getMyName(); %>";
^ ^^

Populating Google Analytics tags with dynamic information using JavaScript and JSP

I am updating a JSP file to create a virtual pageview within Google Analytics. I can see the trackPageView event fire when I click on the right link, but the information I'm trying to pull in dynamically isn't appearing and I'm not sure why.
I have tried a two approaches. My first attempt was to put a statement directly within the GA tag (which always work for _trackEvent). That doesn't generate any information.
The second idea I had was to create a variable in JavaScript with a and then use that variable in the GA code. The problem with this is that I don't know JavaScript very well (or JSP for that matter...learning on the job) and I'm not sure of the correct way to pull in that variable since it's already within the '' from the GA code. Here is my code (currentPDP in the _trackPageView call should be dynamically populated):
<script type="text/javascript">
var currentPDP = <c:out value="${link.key}" /> [];
var _gaq = _gaq || [];
$(document).ready(function(){
$('a.online').click(function (e) {
$('#retail-modal').modal();
_gaq.push(['_setAccount', 'UA-33021136-1']);
_gaq.push(['_trackPageview', '/vp/currentPDP/retailer links page']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
return false;
});
});
</script>
Any advice on how to achieve this would be appreciated. The ultimate goal is to add a specific value (product name) from the current page the person is viewing into the Google Analytics tag so we know what page they were on.
I ended up solving this one by updating a JavaScript function in a different .JSP file that was sending data to this one. I had to add the corresposing parameters to the .JSP file and then I was able to pull in the data I was looking for.
In a JSP you could just insert an "echo" tag like this:
<%= jspVariable %>
In the JavaScript code you can concatenate a JavaScript variable onto another by doing this:
var url = 'http://mydomain.com/other/stuff';
existingVar += url;
What is the specific line of Google Analytics code you are wanting to add to?
Taking a guess that its this line:
_gaq.push(['_trackPageview', '/vp/currentPDP/retailer links page']);
Say you want to replace retailer links page you would do the following for a Java variable:
_gaq.push(['_trackPageview', '/vp/currentPDP/<%= jspVariableHoldingPageURLLink %>']);
Or with Javascript
_gaq.push(['_trackPageview', '/vp/currentPDP/' + 'javaScriptVariableHoldingPageURLLink' ]);

iText - generating files on the fly without needing a PDF file

I am trying to use iText for pdf file generation and I have a question regarding the generation. I would like to serve the PDF to the browser so that the browser displays it, without actually creating a file.
What would be the best approach to achieve this?
One limitation is that I would need to use it from a JSP page - something that would circumvent the "getOutputStream has already been called once" error is what I am looking for.
I would like to serve the PDF to the browser so that the browser displays it, without actually creating a file.
Just pass responsegetOutputStream() instead of new FileOutputStream to PdfWriter.
PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());
// ...
One limitation is that I would need to use it from a JSP page - something that would circumvent the "getOutputStream has already been called once" error is what I am looking for.
Just remove any whitespace outside <% %> in JSP, including newlines. They are implicitly sent to the response by the response writer.
I.e. do NOT
<% page import="foo" %>
<% page import="bar" %>
<%
for (int i = 0; i < 1000; i++) {
out.println("I should not use scriptlets.");
}
%>
(newline here)
but more so
<% page import="foo" %><% page import="bar" %><%
for (int i = 0; i < 1000; i++) {
out.println("I should use servlets.");
}
%>
Or better, don't put Java code in JSP files. JSP files are designed to present template text like HTML, not to do entirely different things. Do that in a normal Java class like a servlet.
Write it to the servlet output stream, remembering to set the encoding to the correct value
This http://onjava.com/onjava/2003/06/18/dynamic_files.html explains how to do it

Combining JSP servlets and Javascript

I have been working with ASP.NET for a few years and am now working on a project using JSP, Struts, and Java so I am fairly new to this.
I have a for-loop in a JavaScript function that looks something like this:
<% int count=0; %>
for(i = 0; i < arrayCount; i++){
jsArray[i] = <%= myBeanArrayList.get(count) %>;
alert("i = " + i + "count = " + count);
<% count++; %>
}
The count variable doesn't increment even if I use <% count = count + 1 %>. I don't understand why that piece of code doesn't do as I want inside the loop. Does anyone have any suggestions on how I can increment the count for the JSP Bean?
That's because you are mixing things.
Your loop is in javascript and the variable count doesn't exists there (beacuse it's java)
You incremented count once, just in <% count++ %>
So if you change to use the loop inside java, the count can work just fine. For example:
<% for( int i = 0; i < ???; i++ ) { %>
alert('<%= i %>');
<% } %>
But it's better separate your javascript from JSP. This can be a pain to mantain.
I kind of agree with b1naryj, but you could try doing the looping in the jsp, and just write the array assignments in javascript, something like:
<%
for(i = 0; i < arrayCount; i++){
%>jsArray[<%i%>] = <%= myBeanArrayList.get(i) %>;
<%}%>
It is ugly, tho...
No one should be using scriptlet code in JSPs. It's a late 90s idiom that has been found to be ugly, brittle, and hard to maintain. Model-2 MVC has swept the field.
You should concentrate on doing things on the server side. If you must write JSPs, use JSTL.
I think the current best practice is to use HTML, CSS, and JavaScript. Get data from services on the server side using HTTP GET/POST or AJAX calls.
You are only looping on the client, not the server. The server code only gets executed once. So, for every iteration of the JavaScript loop, you are using the same value - myBeanArrayList.get(0). View source to look at the generated HTML code and that will probably help to clarify the problem.
Edit: Instead, use server-side code to build a JavaScript array literal. I don't really know JSP, and my Java is a little rusty, but wouldn't this work?
var jsArray = <%= new JSONArray(myBeanArrayList) %>;

Categories