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');
?>
Related
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.
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>
Is there an easy way to send HTML from a servlet to a JSP, using AJAX.
I've already figured out how to make AJAX work with servlets dynamically, but now I want to press a button on a form and generate HTML based on text-input.
Is it possible, and if so, how, to send just pieces of HTML to an existing HTML page?
Example,
I have a basic form where you can input your age, and based on the age the text has a different size/color. So, you send for example, 25 as your age to the servlet, and it send back a piece of HTML like this <p STYLE="font-size: age;"> to the page.
Through ajax call you can get the output result either a string, html or a Json object that will be parsed and results can be displayed over JSP/HTML. So for sure you can send html code segment from servlet to jsp through ajax call.
For example you can use this approach--
1. Take a string variable in your servlet.
2. Put appropriate html string as per your conditions in this string variable
3. send this string as a response from servlet like:
response.setCharacterEncoding("UTF-8");
response.getWriter().write("your string variable here");
4. In your ajax call do like this:
success : function(dataString) {
document.getElementById("containerId").innerHTML=dataString;
},
where containerId is the id of html element (like div or span) where you want to display output html.
The easiest approach, without client-side javascript libraries, would be to point an HTML form to an iframe, just like
<iframe name="myIframe"...>
<form target="myIframe"...>
And submit your form as many times as necessary. The HTML returned by the servlet would load itself in the iframe element.
If you like AJAX and client-side javascript libraries, you can find very easy programmatical ways to do this in jQuery and similar libraries.
Basically your servlet can generate any kind of content, e.g. JSON, HTML etc.
You'd then send that content back to the client and integrate it into the page.
How that is done depends on the type of content.
Example:
You issue an AJX request (e.g. by using jQuery's ajax functionality) and your servlet generates plain html. When your JavaScript receives the anser you just replace the relevant part, e.g. by replacing the content of some defined element.
If you used JSON instead, your servlet might send data only instead, e.g. a font size based on the age as in your example. You'd then use JavaScript to access that JSON data and perform relevant operations, e.g. by changing the style of the paragraph.
I have to write an HTML report from a java class which contains the source code of web pages. So the problem is that as soon as the source of a web page is encountered it is thought of by the browser as being the the end of html tags on the main report page and so the output is not renderd correctly. An example is shown below :
<html>
<body>
<li>
<pre>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
The page was not found on this server.
</body>
</html>
</pre>
</li>
</body>
</html>
I want that everything inside the pre tags must be taken as normal text and not html markup. I tried replacing < with < , > with > , & with & etc.. but it doesnt seem to work. Any tips on how to make this possible?
EDIT :
This is what i tried (a is the part inside pre tags)
File aFile = new File(filename);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(aFile,aFile.exists()));
a.replaceAll("<","<");a.replaceAll(">",">");a.replaceAll("\"","&;quot;");a.replaceAll("&","&");
out.write(a + "\r\n");
out.close();
}
EDIT 2:
So this correct solution involved a=a.replaceAll(...), but another thing to note is that if i replace < with > and later on i replace & with & (like i do in the above example), It will againn mess my output(< will become <). So the order must also be changed(replcae & first and then <).
In Java, String objects are immutable. That means a.replaceAll doesn’t change a but returns a new String object in which the replacement took place.
So to fix this, you need to work with the returned object instead:
a = a.replaceAll("&","&").replaceAll("<","<");
And you actually only need to replace the & and < for your specific application.
do:
a = a.replaceAll("<","<");
instead of :
a.replaceAll("<","<");
and same for others...
As replaceAll method doesn't change the string, it rather returns a new one
Well.. replaceAll may work.. However, I'll always prefer to use StingEscapeUtils as ..
a = StringEscapeUtils.escapeHtml4(a)
The sequence you post in the comment:
a.replaceAll("<","<");
a.replaceAll(">",">");
a.replaceAll("\"","&;quot;");
a.replaceAll("&","&");
won't work, since the replaceAll() method doesn't change the String it is called on. It can't, Strings are immutable in Java.
Also, as #Rishabh points out, your last replace call will mess up the previous replaces, so you need to change the order.
You need to do
a = a.replaceAll("&","&");
a = ...
Or, just do them all without saving the intermediate result:
a = a.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll("\"","&;quot;");
Also, you should probably use the replace() method instead of replaceAll(), there is no need to use regexes in this case.
Replace this line:
a.replaceAll("<","<");a.replaceAll(">",">");a.replaceAll("\"","&;quot;");a.replaceAll("&","&");
As this:
a = a.replaceAll("<","<").replaceAll(">",">").replaceAll("\"","&;quot;").replaceAll("&","&");
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 ;-)...