How do I prevent jsp scriptlet from execution? - java

when i run the program, both statements inside the condition got executed
<script>
if (true) {
<%System.out.println("true");%>
} else {
<%System.out.println("false");%>
}
</script>

Java and JavaScript are completely different—their similar names notwithstanding. They have as much in common as the words “pain” and “painting”.
JSP code is executed in the server, before the user ever receives the page.
JavaScript is executed on the end user’s computer, after the server has executed all of its code, assembled the page, and delivered it to the user’s browser.
The server doesn’t process any JSP content other than JSP tags, or known tag libraries like JSTL. That <script> element and its content is simply added to the final page as is, without ever being interpreted or executed.
In other words, if (true) means nothing to the server. It ignores the JavaScript, and only executes the <%…%> parts.
When the page is finally delivered to the browser, the source will contain this:
<script>
if (true) {
} else {
}
</script>
…because the JavaScript was not processed in any way on the server side. JavaScript in HTML pages runs in browsers, not on the server.
You probably want something like this:
<%
if (true) {
System.out.println("true");
} else {
System.out.println("false");
}
%>
Not that the above does not need to be in a <script> element, and in fact it would not make sense to put it in one—because <script> contains JavaScript and this is server side Java code, not JavaScript.

Related

I want to use java variable in single jsp page

<%!
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.

Reading in text from a text file using java / jquery without a webserver

I have used the jQuery.Get() as well as the $.Get() methods to do this but this does not seem to work.
<head>
<script type="text/javascript" src="jquery-2.1.3.min.js" > </script>
<script language="javascript">
function Read()
{
alert("start");
jQuery.get('/spec.txt', function(result)
{
alert("get");
if (result == 1)
{
alert("1");
$("body").html("<p>Specials</p>");
document.getElementById("specials").innerHTML = "<H1>Specials</H1>";
}
else if(result == 0)
{
alert("2");
$("body").html("<p>No Specials</p>");
document.getElementById("specials").innerHTML = "<H1>No Specials</H1>";
}
});
}
</script>
</head>
<body>
<button onclick="Read()">Specials</button>
<div id="specials">
</div>
</body>
</html>
I want to have a text file in my webroot folder that will only contain the values of 1 or 0. This will be used to determine if there are specials or not (this text file will be altered from another page). The value of this text file is to be read into the webpage and that will determine the course of action the if statements are programmed to. I have attached the code I am currently using to do this but I can't seem to get the $.get() / jQuery.get() to execute. You will notice I am using the alert() method to check the steps through the code but it does not execute the alert("get") immediately after the jQuery.get().
I am not using a webserver which I am assuming is the issue. I am simply running the index.html off my hard disk in the webroot folder. The IF statements are to fire depending on the value of read in from the text file named spec.txt
Please bare in mind I am new to web coding with jQuery and Java but I'm adept at simple HTML / CSS coding. This is my first attempt at dynamic web content like this instead of a static site. The site will eventually be hosted on a webserver if that helps with your answer.
You can't make ajax requests from file:// protocol. It's a security restriction.
Files loaded with file:// are always considered as coming from different domains, you can't bypass this feature.
But... If you are using chrome and just want to test it locally to put in a webserver later, you can disable this feature by running chrome in a unsafe mode
path/to/chrome.exe --disable-web-security
If you are using firefox. You can type in your URL about:config an then go to
security.fileuri.strict_origin_policy -> false
It's ok for local testing only. Don't expect the users of your application to disable that as well or you will be creating a big security problem. Be aware you are disabling all browser security and it will be open for malicious program
Just install a simple web server and have fun!

How do I inject another JSP page into a <div> when clicking a link?

I have two different divisions in a JSP page. One contains a menu of links, when clicked the div2 (id-content) loads different pages accordingly. I am doing something like -
<div id="menu">
<ul class="navbar">
<li><a name="login" href="Login.jsp" onclick="changeContent()">Login</a>
</li></div>
and in the script I have something as -
<script language="JavaScript">
function changeContent() {
document.getElementById('content').load('Login.jsp');
}
</script>
I also tried -
document.getElementById('content').innerHTML=
"<jsp:include page="Login.jsp">";
None of the ways worked. Please suggest how should I
Try jquery..
function changeContent() {
$('#content').load('Login.jsp');
}
The solution is to use Ajax, which will asynchronously retrieve your page content that can be pasted in with the innerHTML method. See my answer to a similar question of how an Ajax call works and some introductory links.
As to why your examples in your answer don't work, in the first case there is no load() method on an Element object (unless you've defined one yourself and not shown it). In the second example, as one of the question comments says, there is probably something causing a syntax error in the javascript.
As an FYI, when there is a syntax error in some javascript in a web page, the current expression being parsed and the rest of the <script></script> block will be ignored. Since this is inside a function declaration, that function will never get defined.
For instance, an embedded quote in the included page will end the string for the innerHTML assignment. Then the javascript parser will try to parse the remainder of the HTML causing a syntax error as the HTML will not be valid javascript.
We use jquery. Add a click event handler to the anchor elements. In the click handler call $('#content').load(your_url);. You might want to use the load(url, function() { ...}) version. More info here http://api.jquery.com/load/
Your initial page comes down from the server. It's displayed by the browser. When you click on a link (or a button) in the browser, you want to fill the second div with new HTML. This is is a perfect job for an AJAX request. What the AJAX object in the browser does, is to send a POST (or whatever) string to the server. And then the Ajax object receives the HTML response back from the server. And then you can display that response data which the AJAX object contains, anywhere you want.

is their any to assign or get Javascript variable to java variable?

......
<%
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.

checking whether the variable is true or not

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.

Categories

Resources