inline java makes causing javascript to not execute - java

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(); %>";
^ ^^

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.

JSP expression language not working when evaluating variables

I am new to JSP and working with Tomcat 8. The problem is that JSP EL is not working properly. Like when i write ${1>2} it gives the right output but when I put a variable name in it it does not give the output. I have this in my code
<%# page import = "java.util.*" isELIgnored="false"%>
but it is still not working. This is my code:
<%
String GuessErrorMsg = null;
if (GuessErrorMsg != null) {
%>
<div class='bad-field-error-message'>${GuessErrorMsg}</div>
<%
}
%>
i found the problem in my code due which i could not get the EL expresion evaluated.
so i am sharing it with everyone. it may be a very beginner's mistake thats what I am.
the problem was that i have not set the variable using setAtrribute(Expression,variable) .thats why i wasnt getting the value .

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' ]);

How do I pass a New line character to JavaScript from my Servlet?

I'm setting the following in the request attribute:
confirmMsg = "REf No: \n 112";
req.setAttribute("confirmMsg", confirmMsg);
I need the above to be displayed like(in alert box) :
Ref No:
112
I'm using the following onload function in my JavaScript to show the message on loading the page.
function onLoad() {
var msg = "${confirmMsg}";
if(msg != null && msg != "") {
alert(msg);
}
}
The above throws a script error? How do I pass the newline character?
The \n needs to be JavaScript-escaped to be put in a JavaScript string literal.
Use commons-lang StringEscapeUtils.escapeECMAScript() to eascape the message, and pass this escaped message to your JSP.
As I mentioned, do not confuse JSP with JavaScript.
What you want to do is output a string message from your JSP/Servlet (JSP is a Servlet) to be used in a JavaScript code block.
To do this your message needs to be encoded for JavaScript, such as using the StringEscapeUtils.escapeECMAScript method described by JB Nizet.
Then you need, in your jsp or servlet creating the response, to output the variable where you want it for the javascript to act upon, for this you do
<%= confirmMsg %>
and not ${} as that is an expression language which is not always available in every jsp.
In short, change from "${confirmMsg}" to <%= confirmMsg %> or <%= (String)request.getParameter("confirmMsg") %> // or request.getAttribute and so on

How to transfer java array to javaScript array using jsp?

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;
<%}
}%>

Categories