This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 5 years ago.
I want to read a jstl variable in a javascript function.
JS code submits a form.
$("#userSubmit").on('submit', function () {
document.getElementById("userForm").submit();
});
So in server code -
request.setAttribute("userId", 435);
and after the page is loaded -> in the javascript code -
$("#textBoxInp").keyup(function() {
// I want to access the userId here.
// in html code i can acccess it using JSTL syntax ${userId}
});
Just write the Expression Language directly in your JavaScript code:
$("#textBoxInp").keyup(function() {
var userId = '${userId}';
});
Note that this won't work if the JavaScript code is placed in a external file and is invoked in the JSP. In this case, you may refer to one of the four ways that BalusC explain here: Mixing JSF EL in a Javascript file (he explains five, but one of them is JSF specific).
One way is as suggested by Mendoza, but it will not work in case of having separate Javascript file.
in that case, another way is adding hidden field in JSP page, and reading same from Javascript.
JSP code:
<input type="hidden" id="xID" name="x" value="${myAttribute}">
JS code:
var myAtt = document.getElementById("xID").value;
If you want to access jstl variable in a javascript script function, you won't be able to access them directly. Here's a roundabout way(easy to implement) to do it.
In the HTML code have a paragraph with the required variable.
<p id = "var" disabled = "disabled">${variable}</p>
Access the variable using .innerHTML inside the JavaScript function.
function myFunction() {
var jstl_var = document.getElementById("var").innerHTML;
}
totalClients is jstl variable and to read in javascript block please see below
<script type="text/javascript">
$(document).ready(function() {
var tc = "<c:out value='${totalClients}'/>";
});
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.
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 am newbie to external javascript files (*.js). Basically I have my JSP ready but my manager wants me to add graphics in it.
So I found some *.js files. But I don't know how to communicate between them and my JSP page.
I want to pass data from jsp to external .js file.
Is there any mechanism to do that?
For e.g:-
Demo.jsp
out.print(request.getAttribute("Name"));
Now I want use/pass/set above value to main.js file how to do that?
<script type="text/javascript">
var myJavascriptVariable = <%= request.getParameter("Name")%>;
//or .getAttribute("Name")
</script>
This could do the trick, it will make a global Variable which could be accessed in main.js. When you have GET Parameters you could also use only JS:
var paramarr = window.location.search.substr(1).split("&");
var params = {};
for (var i = 0; i < paramarr.length; i++) {
var tmparr = paramarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
or a bit shorter:
var params = {};
// parse URL's GET parameters and iterate over them
window.location.search.substr(1).split("&"),forEach(function(el) {
var kv = el.split('"'); // split into [ key, value ] array
params[kv[0]] = kv[1];
});
Now you can access the parameter in JS via:
params['name']
Personally I would use AJAX (e.g. with the help of JQuery) to get Data for my JavaScript files, you can look at that at http://api.jquery.com/category/ajax/shorthand-methods/ (2018 edit: kust use native ajax calls or whatever JS framework is hyped this week ;-) )
If you are using .js file you can't write jsp sriptlet in it.
If you need to call value in .js file there is one simple way.
Assign values to input elements in .jsp page.(If you are not using values in .jsp page assign values to hidden input elements)
Then include.js file in your .jsp page
get values as javasript or jquery methods.
Ex:-
value= document.getElementById("element_id").value
OR If you are using jquery you can get as
value = $("#element_id").val();
You can declare a global js variable and assign the value.
<% String myValue = (String)request.getAttribute("Name"); %>
var global1 ='<%= myValue %>';
This question already has answers here:
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
(5 answers)
Closed 5 years ago.
I have a dropdown box in JSP, listing a Java object (accessing the object through the MVC controller's addAttribute). Now, on selection of an option from the dropdown box, I would like to display the selected employee's other details (example - ${employee.employeeCV}, ${employee.employeeName}) in a div. I have a JavaScript function for that (displayCV()). But I am not sure how to do this.
JSP -
<c:forEach items="${employees}" var="employee">
<option value="${employee.id}" onclick="displayCV();">
${employee.employeeName}
</option>
</c:forEach>
<b>CV:</b>
JavaScript
function displayCV() {
var valueSelected = $('#employeeList').val();
var div = $('#candidateDiv');
}
How can I do this?
You can't access Java classes directly from JavaScript. You have to use some kind of web service communication between the JavaScript (client) and Java (server). You can make use of the onchange event which will send a request to the server to return XML/JSON which you can parse to get the data (I see you're using jQuery, and it has parseJSON method already) and update the corresponding node in the DOM.
Another easier way, though, that is not multi-user friendly (because it can't detect updates) is to "convert" the Java object to JavaScript and update the data using that object (still using onchange). Something like:
// This is JavaScript code written in the JSP
var employees = {
<c:forEach items="${employees}" var="employee">
"${employee.id}": {
name:"${employee.employeeName}",
cv:"${employee.employeeCV}",
},
</c:forEach>
}
Now when JSP parses this, it would generate, for instance:
var employees = {
"1": {
name:"foo",
cv:"cv1",
},
"2": {
name:"bar",
cv:"cv2",
},
}
Meta of what LeleDumbo said here already:
First, you must understand that JSP is a server-side view technology, whereas JavaScript typically runs on the client (browser).
Now, how you solve the problem in hand. So, you can make an Ajax request from your JavaScript code, which will fetch you the data in JSON/XML format. Then, you can present that data in the browser using JavaScript.
Further reading: jQuery Ajax API and code samnple snippets
Call the function on the onchange event of select instead of onclick of options. And use:
document.getElementById('GrdDamagedstock_tplRowEdit_ctl00_cmbFromBin').options[ele.options.selectedIndex].innerHTML;
to get the selected value.
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 ;-)...