Passing an HTML string to jQuery function - java

I'm working on an application which retrieves some HTML code from a record in a database. That strings then gets taken and inserted inside of a specific div. Right now I'm accomplishing this by passing the variable from Java and printing it within the div in the JSP. Now I'm trying to use an external jQuery function to accomplish this task and I'm struggling with how to pass this String to the jQuery function.
I tried something like this:
<script>
var message = <%=message %>;
</script>
<script src="files/js.js" type="text/javascript"></script>
But it can't seem to interpret the var once it hits the external function (I tried using StringEscapeUtils but that didn't fix the issue).

try:
var message = '<%= message %>';

var message = '<%=message %>';
$(message); // we have a jQuery object with a property
// for each html element in the message string!

When you run into problems like this, view the source of your page. How does message render? My guess might be
var message = Passing an HTML string to jQuery function;
Which isn't valid. Enclosing the code in apostrophies will fix this case.
var message = '<%= message %>';
I also usually put global objects like this on the window object so it is easier to find
window.message = '<%= message %>';

var message= <%= message %>;
You not only need to put some quotes around the message text, you also need to escape it suitably for a JavaScript string literal. Otherwise a quote in the message will break it, and potentially open you up to cross-site scripting attacks.
var message= '<%= message.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") %>';
I think that's the right number of backslashes, but the interaction of Java String literal backslashes and regex backslashes balloons them out of all sanity. Also control codes like newlines would need escaping if you need to include those.
All in all it might be best to hand the task off to a JSON-encoding library which will output all kinds of JavaScript types properly, not just strings. eg. with json-simple:
var message= <%= JSONValue.toJSONString(message) %>;

Related

Fetchinng JSON data from servlet to display on JSP [duplicate]

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.

Remove newlines and whitespace from jsp

I need to store the html retrieved from a <jsp:include> in a javascript variable. So I will have something like this
<script>
var html = '<jsp:include page="...">';
</script>
The problem is the jsp file has lots of whitespace and newlines which makes the javascript invalid! I tried using the trimDirectiveWhitespaces directive as suggested here, but that does not remove newlines.
How can I remove newlines as well from html so it can be a valid javascript string?
Or, another solution is welcome as well.
EDIT:
The snippet should eventually look like this (but with many more options):
<script>
var html = '<label class="someClass">Label</label><select><option value="val1">Value</option></select>';
</script>

Convert an Entire HTML Page to a Single JavaScript String

I need to turn an entire HTML document into one, valid JavaScript string.
This is a process that will need to be done regularly.
For example:This:
<html>
<!--here is my html-->
<div id="Main">some content</div>
</html>
needs to become this:
var htmlString="<html><!--here is my html --><div id=\"Main\">some content</div><html>"
Based on what I've ready my initial thought is to read the contents of the file with Java and write my own parser. I don't think this would be possible with a shell script or the like? (I'm on OSX)
Can someone recommend a good approach?
Similar Questions I've Read
Reading entire html file to String?
convert html to javascript
Try this live, jsFiddle
JS
var htmlString = document.getElementsByTagName('html')[0].innerHTML;
console.log(htmlString);
HTML
<p>Hello</p>
<div>Hi div</div>
How about a jQuery GET request?
e.g.
$.get( "http://www.domain.com/some/page.html", function( data ) {
// data == entire page in html string
});
It will work on php script also (resulting html output that is).
Alternatively, if you want to achieve this PHP, something like this will also work:
<?php
$html_str = file_get_contents('http://www.domain.com/some/page.html');
?>

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.

Question about executing javascript post-processes in Java app

Traditionally we have always used xml in the response which is parsed by a Javascript method to execute post processes. I came up with a new, simpler implementation which uses a hidden input set by a requestAttribute and executed in an ajax callback.
JSP:
<%
String jsPostProcess = (String)request.getAttribute("jsPostProcess");
if (jsPostProcess!=null && jsPostProcess.trim().length()>0){
%>
<input type="hidden" id="jsPostProcess" name="jsPostProcess"
value="<%= jsPostProcess %> "/>
<% } %>
AJAX CALLBACK:
var callback = {
success: function(response) {
var div = $(divId);
if (div){
div.innerHTML = response.responseText;
}
var jsPostProcess = $('jsPostProcess');
if (jsPostProcess)
eval(jsPostProcess.value);
},
failure: function(response) {
alert('Something went wrong!');
}
}
SERVLET CODE:
request.setAttribute("jsPostProcess", jsPostProcess);
It works beautifully, and it is so much simpler for adding js post processes to virtually any call no matter how simple or complex the functionality is. No need for customized js methods for parsing.
Curious if anyone could identify any potential problems with it (such as security issues?) or make any suggestions for other alternatives. We currently use Prototype and YUI 2 on the front-end.
First, there's no need for that unpleasant scriptlet code:
<c:if test='${not empty jsPostProcess}'>
<input type='hidden' id='jsPostProcess' name='jsPostProcess' value='${jsPostProcess}'>
</c:if>
Next thing is that I hope that somewhere before this point the "jsPostProcess" value has been scrubbed so that it doesn't break the markup (like, in case it includes quotes).
Just calling eval() on the value like that seems a little dangerous, though perhaps you know pretty well what it's going to be.
Finally I would offer the suggestion that as an alternative to that, if the "post process" code isn't too big you could send it back in a response header. Then you wouldn't have to drop any meaningless markup into your page.
Oh, also finally: you might want to make the <input> be disabled. Or, alternatively, you don't even have to use an input: you can use this trick:
<script id='jsPostProcess' type='text/plain'>
${jsPostProcess}
</script>
Because the "type" attribute is "text/plain" the browsers won't try to execute that code, and you can get the "text" of the <script> element whenever you want.

Categories

Resources