You’re very much confusing the difference between server-side code and client-side code. Conceptually think of them as entirely separate. Your server-side code is this:
boolean check = false;
System.out.println("this runs ! ");
Two things to notice:
- You define a variable that you never use.
- The message will always print to the output because there’s no reason why it shouldn’t.
Your client-side code is this:
function test(){
if(!check) {
alert("validation fails");
return false;
}
else return true;
}
If you’re successfully invoking test()
you’ll find that this will produce an error on the browser’s console because check
is undefined.
As for how to correct this, that really depends on what you’re actually trying to do here. “I want to use a Java variable in JavaScript” is not the problem you’re trying to solve. Stepping back from that, there must be a reason behind writing this code. Whatever that reason is, it’s very likely that there’s a better way to do this than to continue down this path, given that you took a wrong turn on the path a while ago.
However, if all you want is to output that variable to JavaScript, you may be able to do something like this:
if(<%=!check%>) {
alert("validation fails");
return false;
}
This would output the result of evaluating !check
on the server, and that result would be a raw string embedded in the JavaScript code. I’m not 100% sure if Java/JSP/etc. evaluates that way, but hopefully you get the idea. Examine the resulting client-side code to see what it actually outputs of course. Ideally it would end up something like this:
if(true) {
alert("validation fails");
return false;
}
Granted, if this bit of hand-waving is covering up more problems:
/*
* java code for updating test variable for validating values on the jsp page
*/
Then we won’t be able to determine that within the scope of this question.
solved alert() not working in JSP