i am using jsp format eclipse 3.2 tomcat server 5.5. I have a problem to convert var variable (javascript) to int variable(java). what is the correct way to do this?
In html body, i use this method to throw:
String qwerty = Integer.toString(f);
String asdf = Integer.toString(d);
System.out.println("CONVERTED VALUE : "+qwerty+" "+asdf);
%>
<input type="hidden" id="balance" name="balance" value="<%=qwerty%>" />
<input type="hidden" id="loop" name="loop" value="<%=asdf%>" />
<%
System.out.println("VALUES : "+balance+" "+loop);
In html head(script):
<script>
function myfunction()
{
var looping = document.getElementById("loop").value;
var balancing = document.getElementById("balance").value;
<%
String loop="<%=document.writeln(looping)%>";
String balance="<%=document.writeln(balancing)%>";
int balance = Integer.parseInt(balancing);
int loop = Integer.parseInt(looping);
%>
..........................cont
how to convert this var to string?
You need to understand that Java is run at the server side, while JavaScript is run at the client side. They are running in different contexts and tiers and most likely physical machines (cheers, localhost). In the context of your question, java code is used to produce HTML/JS (on the server) that is used to communicate with the end user typically within the browser (on the client). So they don't "see" each other nicely/straightforwardly.
As soon as you understand these facts and remember the basics of HTTP, the server-client communication is handled by means of request-response model. In this light you can "print" data in your view file to send information to the client, as in var passedFromJava = ${bean.data}; so that it ends up in response body. Reversely, when client fires the request (submits the form with e.g. input element) all of the inputs of the submitted form end up as request parameters and could be obtained in Java as String fromHtmlPage = request.getParameter("inputName");. You can of course add such parameters from JavaScript side on in, for instance <input type="hidden"> element, add them as data to an AJAX request, etc. But do understand that direct JavaScript is invisible to Java: communication means is the HTTP.
By the way, usage of scriptlets (%) is not welcome nowadays. For more information consult the classics: How to avoid Java code in JSP files?.
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.
<%!
public void runJavaMethod(int id)
{
%>
<%
try{
String icd = request.getParameter("icd");
String inm = request.getParameter("inm");
String istk = request.getParameter("istock");
String sstk = request.getParameter("sstock");
String upr = request.getParameter("uprice");
String spr = request.getParameter("sprice");
r = s.executeQuery("select * from itemsyncdata");
while(r.next())
{
s.executeUpdate("update itemsyncdata set itemcode='"+icd+"',itemname='"+inm+"',instock='"+istk+"',storestock='"+sstk+"',unitprice='"+upr+"',storeprice='"+spr+"' where id='"+a+"'");
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<%!} %>
And I am Calling Function from html like
<input type="submit" id="btnSync" value="Sync" class="button" name="Sync" onclick="<%runJavaMethod(r.getInt(1));%>"/>
So We want runJavaMethod Parameter.
onclick="<%runJavaMethod(r.getInt(1));%>"/>
HTML/Javascript Plays on client side and JSP/Java plays on server side.
Simply you can't. You might misunderstand that JSP and HTML/JavaScript existed on same document. Yes but JSP part compiles on server side itself comes to client.
What you can do is you have to make a server request. Most probably look at Ajax requests.
You are trying to mix up two languages i.e., Java and Javascript/html together i.e., onclick is a Javascript event and you can't call runJavaMethod from Javascript.
In simple words, you can't directly call a Java method (present inside the scriptlet) using Javascript because all of your JSP code produces (becomes) html when it is loaded from the server.
So, if you have to fix the issue, upon onclick, you need to call an URL which hits a servlet/controller method on the server to do the job (i.e., executes the business logic).
One more important point is that Scriptlets are legacy code and I strongly suggest not use them to generate or manage the html content, rather use JSTL so that there will be a clear separation between the concerns (i.e., business logic and user interface requirements).
Also, I strongly suggest you read the JSP best practices from here and follow them.
You are mixing to two different things. JSP is server side code and it's rendered response is the HTML that is send back to the browser.Javascript is pure client side in your case.
If you really want invoke a server side processing than create a simple Java script function with Ajax call and get response back which u can use it.
I suggest send all the logic of JSP in backend class not a good practice to put in the jsp. JSP is ideally for UI design.
I have this code:
<script type="text/javascript">
function foo() {
var test =///value;
<!--and i jave java code inside this script!-->
<% String str= // i want to assign it to test value%>
}
</script>
How can i assign test to str ??
How can i assign test to str ??
No simply you cannot.
Java plays on server side and javascript on server side. A client doesn't execute the java code.
You can assign a java value to javascript variable with jsp or Expression language on server side.
To send a javascript value to java you have to make a server request, So the server process your string and send the results back to client.
Most probably you are looking for AJAX request.
Ajax.
Do not confuse that JSP and java script existed on same document(or file). Yes but JSP part compiles on server side and JavaScript executes by browser.
A clear cut example found here for a start.
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.
......
<%
int s = (int) (Math.random() * 1000000);
%>
.................
<body bgcolor="<%=s%>"> .......
it shows no error and executing but on viceversa it shows error.I want JS varivble in java is their any otherway to do?
.....
var a=10;
<%
int s = a //is their any other way
%>
i know getParamater() method i want another alterntive way
No, you cannot do it like that. The Java is in a JSP that is executed on the server to generate a web page (in this case containing Javacript) which is returned to the user's web browser. When the web browser receives it typically renders it, and the Javascript is executed immediately or in response to some user action. By the time that the Javascript executes, it is on the wrong machine, and the execution context for the original JSP has gone away.
If Javascript needs to pass information to the server, it must do it by means of a new HTTP request. It could use an XmlHttpRequest object explicitly, or it could put information into the elements of a <form> in the current web page, or something similar.