Is this possible? I want to be able to pass java bean data into javascript objects, but I'd really prefer not to muck up my jsp pages with a bunch of inline script tags. I like to keep my javascript separate in external files, but how do you accomplish something like this without using inline js?
<script type="text/javascript">
var variableFromServer = '${someBean.someProperty}';
</script>
You can create a JSON file with all the data and either include it inline or fetch the JSON through Ajax - that way you don't clutter the markup with data. See http://json-taglib.sourceforge.net/ for an example of a JSP-JSON template.
I'm not sure if this is worth it but one alternative will be to set the desired value in an input filed with type="hidden" and get it's in js. But this will also pass this parameter in GET and POST request from the form.
You can either do what you're doing in the snippet (do you consider that "inline JS"?), create a div of JSON with data in it (exposed as a single string) and process it, pass JS files through the JSP process (or use a different templating system for dynamic JS pages), etc.
I'm not a huge fan of processing JS files through JSP; I'll often create an object containing all the info my JS needs in a <script> tag at the bottom of the body before including my real JS. It's kind of lazy, but it's straight-forward.
One option that I've used in the past is to configure the servlet container to run the JSP interpreter on *.js files. How to set this up will depend upon what server you are running.
Note that if you want to access any request attributes this way you will need to set them up as part of the request that fetches the JavaScript file(s) (i.e. you will have to have a servlet in front of your JavaScript...or as an alternative you can use an include directive to bring in the scripts instead of a <script src='...'> tag). Session attributes you can access without needing to have a custom servlet in front of your JavaScript files.
I'm a fan of doing it the simple and easy way, so I'd create a single script element that has a minimal number of JS variables set from Java - ideally a single JS variable that is set to an object with different properties for all the different bits of data you need to pass through. Your Java code basically just outputs JSON that will be interpreted as an object literal in the JS. Immediately after that include any external scripts - because they're included afterwards they can use the variables already created.
You can put the above in the head or at the end of the body. (Or in the middle, but that doesn't really make sense.)
<html>
<head>
</head>
<body>
<!-- actual HTML markup here -->
<script>
var variableFromServer = '${someBean.someProperty}',
objectFromServer = /* jsp to spit out JSON here as appropriate */ ;
</script>
<!-- external files included after the above will be able to access
those variables -->
<script src="external1.js" type="text/javascript"></script>
<script src="external2.js" type="text/javascript"></script>
<script src="etc.js" type="text/javascript"></script>
</body>
</html>
You certainly don't need "a bunch of inline script tags" - even if it doesn't make sense to put all the values in a single object at least create all the variables in a single script element, and then all of your other JS can be in an external file.
(Add namespacing as required.)
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 have designed a product recommendation hub using Java and JavaScript in Eclipse. Basic functionality is, if the person enters the product name, it will retrieve the relevant product reviews from the local XAMPP database, perform sentiment analysis on it and dispalys whether the product is recommended or not based on the number of positive or negative sentiments. My questions:
Is it possible to convert this local JSP UI page into a globally accessible web page without modifying my java code?
If Yes, please guide me. If No, please justify to get a clear understanding.
Is it possible using Amazon AWS?
You could load the page via ajax/jquery.
In the target page, create a div tag that will be your placeholder:
<div id="myPlaceholder"></div>
and add some javascript like:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.get("/theurlofthecurrentpage?some=thing", function(data) {
$("#myPlaceholder").html(data);
});
});
</script>
If the JSP control does full postbacks, you may have to update it to handle it clientside. hopefully this helps.
How do I include a JavaScript variable inside thymeleaf for checking a condition?
Tried:
<div th:if="${myVariable == 5}">
//some code
</div>
but it's not working.
What you are trying to do won't work, since Thymeleaf processes the template on the server side and therefore the variables it has access to are the ones defined in it's model.
If you had myVariable in the model on which Thymeleaf is operating, it would work.
If what you want is to set the value of a Javascript variable in a Thymeleaf template, you can do the following:
<script th:inline="javascript">
/*<![CDATA[*/
...
var myVariable= /*[[${myVariable}]]*/ 'value';
...
/*]]>*/
</script>
Inside the script you could have any logic you want including hide/show etc.
Check out this part of the documentation for mode details.
With thymeleaf 3, the CDATA block had to be removed to reference my variable inline or the parser ignored it completely. This syntax worked successfully for me post upgrade:
<script th:inline="javascript">
var myVariable = [[${#vars.myVar}]];
...
</script>
Note: if you also referenced your variables as [[${#ctx.variables.myVar}]], it will no longer work in thymeleaf 3 as ctx no longer has a variable named variables.
I think I understand your question and I don't think it's possible. Thymeleaf does server side rendering and thus it won't use javascript variables since those won't be created on the server.
What you can try is write an initializer function that will hide/show certain DOM elements. You can approach this multiple ways for instance give ids to them and change their class list to add "display:none" style.
<script>
// <![CDATA[
...Your script, here
// ]]>
</script>
I have a servlet based web application which produces two sets of data. One set of data in the webpage which is essential and other set which is optional. I would like to render the essential data as fast as possible and then stream the optional data. I was thinking of writing the essential data to the output stream of HttpServletRequest and then call HttpServletRequest.flushBuffer() to commit the response to the client, but do not return from the servlet code, but instead create the optional data , write that to the outputstream again and then return from servlet code.
What are the things that could go wrong in this scheme ? Is this a standard practice to achieve this goal?
It makes somewhat sense to flush the response buffer directly between </head> and <body> so that the browser retrieves references to JS/CSS resources as fast as possible. It only doesn't make sense to do it in a servlet as it's the JSP who is supposed to be used to generate HTML.
</head>
<% response.flushBuffer(); %>
<body>
(that's one of the 0.01% cases where using a scriptlet is forgiveable as there's no tag which does that; only in EL 2.2 you could use ${pageContext.response.flushBuffer()})
However, most servletcontainers by default already flush the buffer every 2KB and that'll surely cover the entire <head> on the average webapp. You can finetune the response buffer size in server configuration (refer server documentation for details) or on a per-JSP basis using as follows:
<%#page buffer="1kb" %>
Further, flushing the buffer halfway a HTML <body> makes little to no sense as you're dependent on the browser whether it would render a halfbaked HTML body or not. MSIE for example displays nothing until the </body> is arrived.
A completely different alternative is to use JS/Ajax to load the "optional" content asynchronously in the background when the page is completed loading. E.g. (jQuery flavored):
$(function() {
$("#somediv").load("somefragment.jsp");
});
See also:
Web application performance tips and tricks
I would do this instead :
return essential data as normal servlet + javascript to do Ajax calling for optional data. Then essential data will be shown with out wait the optional data.
so the html will look like this:
<html>
<body>
essential data
<javascript to do ajax call>
essential data
</body>
</html>
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 ;-)...