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.
Related
<%!
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 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?.
Here is my function:
var boxName = document.getElementById('searchBox').value;
How can I put the value of boxName inside the scriplet like this?
<%BoxList.getInstance().getBoxListNames().contains(boxName);%>
--Not Possible
You might misunderstand that jsp and javascript existed on same document.Yes but JSP part compiles on server side itself comes to client.
Java script Plays on client side and JSP plays on server side.
What you need is you have to make a server request.And send that string a query parameter.
And please prefer to read How to avoid Java code in JSP files?
......
<%
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.
function add(){
<%if(empRecNum != null && !(empRecNum.equals("")))
{
empSelected=true;
}
boolean canModify = UTIL.hasSecurity("PFTMODFY") && empSelected;
%>
df('ADD');
}
When i click on add, i need to check whether the empSelected is true or not and pass this canModify value. Will this be called?
Is this right way i am checking a Scriptlet inside a JavaScript
A more elagant way to do this
var canModify = Boolean(${canModify});
Use jstl el, it turns more clear what do you intend to do.
The call to boolean will convert the given value in javascript boolean.
Remember:
Boolean(true); // returns true
Boolean(false); // return false
Boolean(); // returns false
You need to get the following concept right: Java/JSP runs at webserver and produces HTML/CSS/JS output. Webserver sends HTML/CSS/JS output to webbrowser. Webbrowser retrieves HTML/CSS/JS output and displays HTML, applies CSS and executes JS. If Java/JSP has done its job right, you should not see any line of Java/JSP code in webbrowser. Rightclick page in webbrowser and choose View Source. Do you see it, right?
The webbrowser has totally no notion about the Java/JSP code on the server side. All it knows about and can see is the HTML/CSS/JS code it has retrieved. The only communication way between webbrowser and webserver is using HTTP requests. In the webbrowser, a HTTP request can be fired by entering URL in address bar, clicking a (bookmark) link, pressing a submit button or executing XMLHttpRequest using JavaScript. In the webserver, the Java/JSP (and Servlet) code can be configured so that it executes on certain URL's only. E.g. a JSP page on a certain location, a Servlet which is mapped on a certain url-pattern, etcetera.
In a nutshell, to have JavaScript to access Java/JSP variables, all you need is to let Java/JSP print them as if it is a JavaScript variable. To have JavaScript to execute Java/JSP methods, all you need is to let JavaScript fire a HTTP request.
See also: Communication between Java/JSP/JSF and JavaScript
The canModify value defined in JSP is never passed to JavaScript. You need to redefine the variable in JavaScript, for example:
<%
if (canModify) { // This is the JSP variable
%>
var canModify = true; // This is the JavaScript variable
<%
} else {
%>
var canModify = false;
<%
}
%>
On a different note, you should abandon JSP scriptlets and switch to JSTL.