preventing string concatenation in javascript function during JSP compilation - java

var result = null;
function setSendButton(userInput){
var clicked=userInput;
result = "<%=mb.myMethod(clicked)%>";
}
where myMethod is a java method called through using jsp tags. it is defined as:
public boolean myMethod(String isClicked){
if(isClicked.equals("true")){
return true;
}else{
return false;
}
}
for some reason stepping i got a JSP compilation error that compiles the code where var clicked value of "true" is not passed and clicked becomes a string during JSP compilation like so: mb.myMethod(clicked) instead of mb.myMethod("true")

It can't work like that.
The Java code in JSP is translated and compiled on the server side before sending to the client's browser. The javascript variable is available only after the JSP is translated and compiled to become a HTML file and sent to the client browser. At that time, The mb.myMethod is already already executed on the server side.
In short, you can passed java code to js assignment but not the other way around.

Wouldn't this work?
var result = null;
function setSendButton(){
result = "<%=mb.myMethod(true)%>";
}

Related

Passing a Function as a String in JavaScript

Apologies if this is a bit of a weird one...
I have a program written in Java which utilises the ScriptEngine to process user provided JavaScript to extend my application. However, this specific question is related to general JavaScript as opposed to Java or it's ScriptEngine, but I am just explaining this to set the context.
I have a function which returns a string when called - let's call it a() as defined below:
var a = function() {
return "this is a";
};
When the user calls this function using a() it works fine and outputs "this is a". However, if the user forgets to include the parenthesis then it outputs my actual function definition - expecting this as I am no longer calling the function.
To catch this I have redefined the toString method of my Object to the following:
a.toString = function() {
return a();
};
This works fine when I use a in a string context as it calls the toString method implicitly, but if I attempt to pass it to a function then it doesn't call toString and I am left with a sun.org.mozilla.javascript.internal.InterpretedFunction.
I have looked at the other Function.prototype methods (i.e. apply, bind, constructor, etc) to try and override the method which is called as the function is passed to another function but none of them fitted the bill. I am basically looking for a way of converting a Function to a string type object whenever it is used without the parenthesis - i.e a === a(). For people who might ask why don't I define a as a string to start with, my function returns a string constructed from other information the user has provided.
Maybe the solution is to make my users write syntactically correct JavaScript, but my users are far from programmers. I could also add some form of pre-parsing which checks for missing parenthesis and adds them in dynamically before I execute it using the ScriptEngine. However, although both of these options will work, I am looking for an easier way.
Neither a.toString nor a.prototype.toString will allow you to forget the parenthesis. .toString allow you to do:
var a = function() {
return "this is a";
};
a.prototype.toString = function () {
return "something";
};
var A = new a;
alert(A + ''); // something
A.toString = function () {
return "something else";
};
alert(A + ''); // something else
You shouldn't want in your code both a() and a return the same thing, this looks like a very bad idea.
An option to get myObject.myVar return a custom dynamic string is defineGetter https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/defineGetter

js function containing php executes when not called

I have the following code within the tag of my page:
<script>
function LogInOut()
{
// Get the current login status
alert("executing LogInOut");
$loginStatus = "<?php echo $_SESSION['login']; ?>";
if ($loginStatus == "true")
{
<?php
echo "<br />script function";
$_SESSION['login'] = "false";
session_destroy();
?>
document.getElementById("loginState").innerHTML = "login";
}
else
{
window.location = 'login.php';
}
}
</script>
I find that the php code executes when the page loads. The function (for debugging) is NEVER called yet the php code executes while none of the rest of the script executes! Can anyone clarify why this could be happening?
thank you,
Shimon
Classic case of mixing Javascript, a client side language, with PHP, a server side language. They run at two different locations and that being said this will never be possible.
PHP runs before javascript and if your trying to mix it with javascript, use it to echo dynamic data. eg:
var logged_in = <?=($_SESSION['login'] ? 'true' : 'false')?> ;
Javascript runs within the browser and after PHP, do not use php code thinking it will run inside of the browser
You will need something to call the function
In your case, call it when page is ready.
$(document).ready(function(){
LogInOut();
});
Or using a console for modern browser type in:
LogInOut();

mixing javascript with java

basically my problem is when I want to mix javascript with java code since I did not take the variable (var nombreRodamiento javascript) when I put the "<%" to start putting java code.
please note the bold line, which is what the compiler does not like.
<script type="text/javaScript">
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {//izquierda
if (listLeft.options.length == 0) {
alert('Ya aprobaste todos los items');
return false;
} else {
var rodamientoElegido = listLeft.options.selectedIndex;
var nombreRodamiento = listLeft.options[rodamientoElegido].text;
move(listRight, listLeft.options[rodamientoElegido].value,
listLeft.options[rodamientoElegido].text);
listLeft.remove(rodamientoElegido);
<%
**String nombreRodamiento = '%> nombreRodamiento;<%'**
for (int i=0;i<listaItems.size();i++){
if (listaItems.get(i).equals(nombreRodamiento))
listaItems.remove(i);
}
%>
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
}
}
</script>
Regards
Assuming that this is all inside of a JSP. The java code (scriptlet, everything inside the <% %> tags) will execute server side, and the javascript will execute client side (in the user's browser). Yet you seem to be assigning a java variable the value of a javascript variable, nombreRodamiento. That is not going to work. The javascript is just text, with no values, execution context, etc, whenever the scriplet is being evaluated.
Java strings require double quotes, and you're missing a semicolon, which Java will not automatically insert.
Assuming this is a part of jsp file java code and js code executes separately. first java code get execute on server side and then the javascript code and that is on client side. Infact the java scriplet in jsp renderes the js code to be executed later on client which in this case is a browser.
Hence one cannot assign javascript variable value to a java variable but the reverse is possible.T
Edit:
I can give you the steps as I dont know your server side implementation.
render the page. You must be rendering the list by some type of array or equivaletn object on server side. save both right and left side element on session.
when the list box do some element exchange. exucute your js code.
you have to update the same on server side so send the selected element index and side information to server side using ajax.
update the server side list objects in the session accordingly. Update db if needed.
From next time render this list box suing this objects on ths server side sessions.
Hope this helps.

Calling PHP function from Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
invoking a php method from java
Never came across with this situation before, so would like to understand / know how to go about this ?
Goal: Call php function from Java
Let's say Java code looks like this
pulic class Testing
{
String userid;
String pass;
String url;
public static void main (String[] args )
{
String value1 = checker ( userid, pass, url );
String value2 = dataGetter ( value1 )
}
public static String checker ( String userid, String pass, String url);
{
// Code to get authenticated
}
public static String dataGetter ( value1 );
}
and PHP code looks like this
<?php
$url;
$size;
function dataGetter( value1, $size)
{
// code to get data from server
}
?>
Will this be possible ? if so can someone explain me how deployment will work ? i.e java being deployed on tomcat and php on apache ?
While they cannot communicate directly, you can have them communicate in the same way that a client browser can communicate with the server, which is to say, using ajax and javascript. Have one page generated through jsp or php (doesn't matter which) load via ajax a php page or a jsp page (or servlet). The result is whatever you want it to be in either case and in this way you can get information from either.
Alternatively, you can make a Java program that opens a connection to a php page and uses what gets returned if you don't want to use a browser.
Of course, I'm assuming you are in the strange circumstance where you cannot simply drop one technology in order to use the other or I would highly recommend that solution over this. However, as these things usually go, if you're too far into your project to back out now, then this will also work for you.
Call the PHP via the command-line or via http using java.net.URL.

Calling JS from an applet works in Firefox & Chrome but not Safari

I have the following code in an applet to call some Javascript (it's a bit convoluted because the fn that's called gets an object from the DOM identified by divId and calls a function on it).
#Override
public final void start() {
System.err.println("start() method called");
this.javascript = JSObject.getWindow(this);
this.jsObjectDivId = getParameter("parent_div_id");
this.initCallbackFnName = getParameter("init_callback");
Object args[] = {this.jsObjectDivId, this.initCallbackFnName};
System.out.print("Calling init_callback\n");
this.javascript.call("callJS", args);
}
The callJS function is:
window.callJS = function(divId, functionName, jsonArgString) {
var args, obj;
obj = $(divId).data('neatObject');
args = eval(jsonArgString);
return obj[functionName](args);
};
In Firefox/Chrome the divId and functionName arguments contain valid strings and everything works fine; the desired function is called on the object hanging off the specified DIV data.
In Safari, the divId and functionName arguments are both reported as a JavaRuntimeObject with values of true.
> divId
JavaRuntimeObject
true
What gives?
LiveConnect is not fully supported in all browsers. Especially, Safari doesn't convert Java Strings to the prober JS equivalent when using call. In your case you can just use eval at the Applet side instead of call and put in a JSON string object with the arguments. Something like:
javascript.eval(callback + "({\"id\":\"" + id + "\",\" ... })")
Basically, you need to know the cross-browser compatible subset of LiveConnect that works.
I've written a blog post that describes the subset: http://blog.aarhusworks.com/applets-missing-information-about-liveconnect-and-deployment/
It comes with a LiveConnect test suite which runs in the browser: http://www.jdams.org/live-connect-test
I had a similar issue with calling a method on an applet in Safari. It was returning a JavaRuntimeObject that I caused an exception when it was user later on.
As pointed out by #edoloughlin I had to use (applet.getMethod() + "") after which point the proper string was evaluated.
The comment saved me a bunch of time so I thought it useful to add here as I can't comment above.

Categories