Interaction between JSP and External javascript files - java

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

Related

Replace equal with semicolon in Java Script Object

I am sending the Map<String,String> object from servlet to jsp whose key is attribute name and value jsonvalue. My Requirement is to collect the value of key in variable that is root here. But when I tried to assign these map object to JavaScript variable i'ts throwing an error because the map object contains the = operator in the data. So to remove the error I assigned = with : manually its working fine.
So please tell me how do I remove the = with : with JavaScript code? Or is there any way to send the data with semicolon from servlet?
The data is coming in this format:
var trees= {dage={"nodeId":3,"value":"0-7","children":[{"nodeId":2,"value":"4-7","children":[{"nodeId":1,"value":"6-7","children":[{"nodeId":0,"value":"7","children":[]},{"nodeId":4,"value":"6","children":[]}]},{"nodeId":6,"value":"4-5","children":[{"nodeId":5,"value":"5","children":[]},{"nodeId":7,"value":"4","children":[]}]}]},{"nodeId":10,"value":"0-3","children":[{"nodeId":9,"value":"2-3","children":[{"nodeId":8,"value":"3","children":[]},{"nodeId":11,"value":"2","children":[]}]},{"nodeId":13,"value":"0-1","children":[{"nodeId":12,"value":"1","children":[]},{"nodeId":14,"value":"0","children":[]}]}]}]},
dpob={"nodeId":6,"value":"4;3;5;6;1;2;0","children":[{"nodeId":5,"value":"0","children":[{"nodeId":4,"value":"0","children":[{"nodeId":3,"value":"0","children":[{"nodeId":2,"value":"0","children":[{"nodeId":1,"value":"0","children":[{"nodeId":0,"value":"0","children":[]}]}]}]}]}]},{"nodeId":12,"value":"4;3;5;6;1;2","children":[{"nodeId":11,"value":"3;5;6;1;2","children":[{"nodeId":10,"value":"5;6;1;2","children":[{"nodeId":9,"value":"2","children":[{"nodeId":8,"value":"2","children":[{"nodeId":7,"value":"2","children":[]}]}]},{"nodeId":15,"value":"5;6;1","children":[{"nodeId":14,"value":"1","children":[{"nodeId":13,"value":"1","children":[]}]},{"nodeId":17,"value":"5;6","children":[{"nodeId":16,"value":"6","children":[]},{"nodeId":18,"value":"5","children":[]}]}]}]},{"nodeId":22,"value":"3","children":[{"nodeId":21,"value":"3","children":[{"nodeId":20,"value":"3","children":[{"nodeId":19,"value":"3","children":[]}]}]}]}]},{"nodeId":27,"value":"4","children":[{"nodeId":26,"value":"4","children":[{"nodeId":25,"value":"4","children":[{"nodeId":24,"value":"4","children":[{"nodeId":23,"value":"4","children":[]}]}]}]}]}]}]}}
I am trying to iterate this map working fine if : is there to get the key.
for (var key in trees){
if(key===attribute_name){
root=trees[key];
break;
}
}
This is the jsp code through which i am getting the data
<script type="text/javascript">
var treeStructure=<%=request.getAttribute("treeData")%>;
<script>
Convert your Map<String, String> into a JSON string using a JSON parse library. Then, set this data into a variable in your JavaScript code (after parsing it properly).
Here's an example using Jackson library.
Java servlet (or whatever controller you use) code:
Map<String, String> yourMap = ...;
//fill your map...
request.setAttribute("theMapAsJSON", new ObjectMapper().writeValueAsString(yourMap));
JavaScript code:
<script type="text/javascript">
var treeStructure = JSON.parse('${theMapAsJSON}'); //naive approach
<script>

Reading a jstl variable in javascript code. [duplicate]

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}'/>";
});

Good practices to follow while mixing Javascript and JSP?

In an ideal world I would like to separate out Javascript to a completely different file and include it in the JSP page. But there are cases were I struggle to follow this rule simply because dynamically generated Javascript is so much easier to write !!
Couple of examples :
1) Locale specific error messages in alert boxes.
<%
Locale locale = ..//get current locale
%>
<script language="JavaScript">
function checkMessage() {
if(document.form.msg.value=='') {
alert(<%= *LocaleHelper.getMessage(locale,"please_provide_message")* %>); //get the locale specific message . mixing Javascript and JSP !!!
}
}
2) Initializing values .Sometimes you need to get values using JSP which will be used inside a javascript method
function computeExpiry () {
var creationDate= <%= creationDate =%>
var currentDate = document.form.date.value;
var jsCreationDate= converToDate(creationDate);
return currentDate>creationDate ;
}
3) Initializing config objects dynamically
var myConfig = {
modal:true,
resize:true,
<% if (lastPage) { %>
showPreviousButton :true,
showNextButton : false ,
showSubmitButton : true,
<%} else {%>
showPreviousButton :true,
showNextButton : true ,
showSubmitButton : false,
<%} %>
As you can imagine, without any kind of conventions , all our JSPs will be a unsightly mix of Javascript and JSP, hard to understand and maintain, with lots of non-reusable javascript code
I am not looking for a perfect solution. I know its easier to do this than try to maintain a pure Javascript and JSP separation. I am looking for suggestions to ease this process and hope lots of people have experience worth sharing.
Mixing JavaScript and JSP makes code harder to read, reuse, maintain and also degrades performance(such JS code cannot be externalized and compressed). Avoid that when possible.
One way is collecting all JSP related variables in one place and factoring out non-JSP codes into another pure/static JavaScript files. For example:
<script type='text/javascript' >
var app = { // global app "namespace" holds app-level variables
msg: "<%= *LocaleHelper.getMessage(locale,"please_provide_message")* %>";
creationDate: <%= creationDate =%>;
btnConfig: {
<% if (lastPage) { %>
showNextButton : false ,
showSubmitButton : true,
<%} else {%>
showNextButton : true ,
showSubmitButton : false,
<%} %>
}
};
</script>
// following JS has no JSP, you can externalize them into a separate JS file
// s.t. they can be compressed and cached.
function checkMessage() {
if(document.form.msg.value=='') {
alert(app.msg);
}
}
function computeExpiry () {
var creationDate= app.creationDate;
var currentDate = document.form.date.value;
var jsCreationDate= converToDate(creationDate);
return currentDate > creationDate;
}
var myConfig = _.extend({ // underscore library's extend
modal: true,
resize: true,
showPreviousButton: true,
}, app.btnConfig);
BTW, in practical application, I recommend module loader library like RequireJS instead of defining global variables primitively.
I try to avoid this but when I have to pass data from back-end to front-end I use a flat JavaScript Object which is created by a Hash in the backend. You can convert Hashes in any language to JSON strings. Place a <script> tag in your HTML page and dump that JSON string in it and assign it to a JavaScript variable.
For example:
<script>
var dataFromBackEnd = JSON.parse(<%= Hash.toJSON(); %>); // I'm just assuming JSP part
</script>
From this point JavaScript should take care about logic. If there is a condition that JS need to take action about it pass the boolean value of it to JS. Don't mix logic.
First you can do is avoing using scriptlets. Instead using it use JSP tags, as JSTL. It will allow you to format your code better.

Send variable using jquery (ajax) and phonegap

I am trying to make a mobile application. One page “allpeople.html” has a set of links which are generated via a loop from based on Information from XML file.
Basically what I want is when the user clicks the link the variable is sent to a jquery (ajax) script on the “showResult.html” page which will have a script (again jquery and Ajax)
So it is linke this
var value1=John;
var value2=Male;
//post variables to the function “theCustomFunction” on resultspage.html
$.post('resultspage.html', function(theCustomFunction:”value1”,”value2”) {
});
//on the showResult.html page
<script>
function : theCustomFunction( value1,value2) {
var name= value1;
var sex= value2;
etc ....
}
</script>
I think jquery is the best. you can send data this way too:
$.post('resultspage.html', {name:'John',sex:'male'});
you can use variables too:
var value1='John';
var value2='Male';
$.post('resultspage.html', {name:value1,sex:value2});

What is the best way to use context-param in JavaScript

In my web.xml I set context param "pathToImages". In my jsp files to get path to my images files I use EL, like this:
<img src="${initParam.pathToImages}"/image.jpg" />
But I have problem with JavaScript. In my js files I have code:
setInnerHTML("somePlace", "<.img src='images/s.gif'>");
I know this isn't beautiful code but it isn't mine :) I cannot get my pathToImages in the same way like from jsp. What is the best way to do this?
Pass it as parameter to the js function: function createImage(path) {..} and invoke it with createImage('${initParam.pathToImages}')
Another, perhaps a better option is to have a js variable and initialize it with the desired value. In the JS file:
var imagePath;
function init(config) {
imagePath = config.imagePath;
}
and in your header:
init({imagePath: '${initparam.pathToImages}'});
If you are using templates to build your pages (i.e., tiles or velocity templates) you could assign the variable in your base template with a scriptlet, like:
<script> var imagePath = '<%= config.getServletContext().getInitParameter("pathToImages") %>'; </script>
Then you can refer to the imagePath variable in your js files.
Not pretty, but I don't believe there is a way to access the servlet context from a javascript file directly.

Categories

Resources