Remove newlines and whitespace from jsp - java

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>

Related

Process Thymeleaf variable as HTML code and not text

I'm using Thymeleaf to process html templates, I understood how to append inline strings from my controller, but now I want to append a fragment of HTML code into the page.
For example, lets stay that I have this in my Java application:
String n="<span><i class=\"icon-leaf\"></i>"+str+"</span> \n";
final WebContext ctx = new WebContext(request, response,
servletContext, request.getLocale());
ctx.setVariable("n", n);
What do I need to write in the HTML page so that it would be replaced by the value of the n variable and be processed as HTML code instead of it being encoded as text?
You can use th:utext attribute that stands for unescaped text (see documentation). Use this with caution and avoid user input in th:utext as it can cause security problems.
<div th:remove="tag" th:utext="${n}"></div>
If you want short-hand syntax you can use following:
[(${variable})]
Escaped short-hand syntax is
[[${variable}]]
but if you change inner square brackets [ with regular ( ones HTML is not escaped.
Example within tags:
<div>
[(${variable})]
</div>
Staring with Thymeleaf 3.0 the html friendly tag would be:
<div class="mailbox-read-message" data-th-utext="*{body}">

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

out.println() does not work

I have homework which I have to use scriptlets in ,
I need to make new line in my jsp page usint out object
I tried to use
<%
out.println();
out.newLine();
%>
but both doesn't work !!! I treid to use
out.flush()
but it doesn't work!!
Perhaps out.println("<br>"); is what you're after. (Remember that the browser in which you're viewing the jsp-page in, interprets the output of your script as HTML, which basically ignores newline characters.)
You can look at the source of the page to see what the jsp-page actually generates.
If you really want to see the verbatim output of the jsp-script, you could do
out.println("<html><body><pre>");
// ...
out.println("</pre></body></html>");
#Alaa - out.newLine() does work. It just doesn't do what you are expecting it to do ... assuming that your JSP is generating an HTML page.
When you use out.newLine(), it adds a newline character to the content stream that you are generating. If you use view source on the page in your web browser you can see the newline character.
But a newline character in an HTML document typically does not result in a line break in the displayed page as rendered by a browser. To get the browser to render line break in the displayed page, you typically* need to output a <br /> element.
* - Actually, there are other ways to get the visual equivalent of a line break involving CSS, etcetera. And within a <pre>...</pre> a raw newline character does get rendered as a line break.
Remember the JSP code is outputting HTML. The HTML will then be rendered by the browser. A single blank line in HTML may not be shown as a blank line on the screen when the HTML is rendered.
You need to either examine the HTML source in the browser and look for the blank line. Or else try output more significant HTML to verify the JSP scriptlets are working like:
<%
out.println("<p>hello</p>");
%>

How do you minify/obfuscate JavaScript code in a JSP that has JSP/JSTL variables mixed into it?

arrays.jsp:
//...
var x = <c:out value="${x}"/>
<c:if test="${empty doExternal}">
processExternalArrays();
</c:if>
//...
I want to minify/obfuscate JavaScript contained in a large JSP file in which numerous JSP/JSTL variables are mixed into the JavaScript code such as in the snippet above.
The code relies on variables populated using server-side logic and then passed to the client-side code, as above.
I'm already minifying my JS files using YUI compressor but I don't know what to do about the JavaScript code in my JSPs.
Is it possible to minify/obfuscate this code, given that it is dynamically created?
Probably the best solution for you would be use Granule JSP tag.
You can download it at
http://code.google.com/p/granule/
code sample is:
<g:compress>
<script type="text/javascript" src="common.js"/>
<script type="text/javascript" src="closure/goog/base.js"/>
<script>
goog.require('goog.dom');
goog.require('goog.date');
goog.require('goog.ui.DatePicker');
</script>
<script type="text/javascript">
var dp = new goog.ui.DatePicker();
dp.render(document.getElementById('datepicker'));
</script>
</g:compress>
...
Have you taken a look at htmlcompressor? In short it's a:
Java HTML/XML Compressor is a very
small, fast and easy to use library
that minifies given HTML or XML source
by removing extra whitespaces,
comments and other unneeded characters
without breaking the content
structure.
It's main function is so compress HTML and XML, but it also comes with JSP tags that can be used to compress inline JavaScript blocks by leveraging YUI Compressor. Check out the Google Code page, especially the Compressing selective content in JSP pages section.
I don't see other ways than fully delegating the job to pure JS with help of Ajaxical powers in combination with a Servlet which returns the desired information on an Ajax request (in flavor of JSON?).
E.g. in Servlet
Map<String, Object> data = new HashMap<String, Object>();
data.put("doExternal", doExternal);
data.put("x", x);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data)); // Gson is a Java-JSON converter.
and in JS (with little help of jQuery since it makes the Ajax works less verbose)
$.getJSON('servleturl', function(data) {
var x = data.x;
if (!data.doExternal) {
processExternalArrays();
}
});
This way you end up with clean JS without server-side specific clutter.
Ensure that your output is gzip encoded (apache mod_deflate). Minimizing the html/js first may make it a bit smaller, but not by much.
If you can't, or don't want to, move your JavaScript out of your HTML, one possibility would be to create a tag handler that wraps the content of your <script> tags:
<script type="text/javascript"><js:compress>
...
</js:compress></script>
The handler could probably extend SimpleTagSupport. You'd then have to investigate the Java APIs for compressors/minifiers, like YUI Compressor or dojo ShrinkSafe, and use them to process the tag body.
Edit: Sorry, I skimmed the other answers and it appears that Zack Mulgrew might be referencing a taglib that already does exactly what I'm suggesting...
Edit2: Yup, JavaScriptCompressorTag. Guess I'll have to up-vote his answer ;-)...

Passing an HTML string to jQuery function

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

Categories

Resources