I want to use java variable in single jsp page - java

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

Related

Return with a 500 error from inside a JSP include

Is there a way to, from inside of a jsp:include page, get its requesting page to respond with an HTTP 500 error? I've tried using the response.sendError(418, "I'm a teapot.");, but that only works in the JSP that contains the jsp:include, and only if it is the first line because you can't call it after the response has been committed. What I have is this:
Index.jsp:
// other HTML
<jsp:include page="Exapmle.jsp">
<jsp:param name="aVariable" value="aValue" />
</jsp:include>
// other HTML
Example.jsp:
<%
String aVariable = request.getParameter("aVariable");
if (aVariable != null && !aVariable.trim().isEmpty) {
// code to generate content
%><%=someContent%><%
} else {
response.sendError(418, "I'm a teapot");
}
%>
So is there any way to do this? I'm doubtful based on how JSP's work, but hoping somewhere here can help. Also, servlets aren't an option (right now, at least).
If you get it to work, you shouldn't rely on it to always work on all platforms and future updates. As you state correctly: Once the response has been committed (e.g. all the HTTP headers are on the way to the client) there's no more way for the server to add any other HTTP headers. Let alone change the status code.
That's the reason why JSPs are considered the VIEW layer of an application, not the CONTROLLER. The times when all application logic was written in JSPs are long over and you should have proper request handling somewhere (if only in a servlet, but probably rather in a more powerful abstraction/framework) - decide about the result and either redirect to an error message or the proper visualization in that code.
JSP is good to render the content that you send along with the proper status code. Not to decide which status code to send.

call a java method when Click on a html button without using javascript

i work on JSP and i want to call a java method(Function) on Click on a html button without using<script></script>.how?
i try to write this code:
<button onclick="<%po.killThread();%>">
<font size="4">Kill</font>
</button>
but it doesn't work... so please help me.
thanks
You're misunderstanding how server-side programming works. When you load that page, the webserver will get to the line <button onclick="<%po.killThread();%>"> and will immediately parse and execute the JSP snippet, in your case po.killThread(), and replace everything between the <% and %> with the return value of that method, if any. And all these happens on server side, before client receives any thing. (Note that this will only happen if that page is not already been loaded and compiled into a Servlet by the server.)
Thus, the HTML that client receives, will be something like, <button onclick="some return value or nothing">, which means that nothing will happen when you press the button. If you want to execute further JSP commands on the button press you will need to make a new request to the server - for example, by redirecting the page.
This will call the function killThread when you open the website.
Try to redirect to another jsp which calls the function.
this will not run at all because after the jsp page is compiled it will return the po.killThread() value but will not call this method
You can see this by viewing the page source
JSP is a server-side technology. Did I say server-side?
In order to understand how JSP works and to clear any misconception, JavaRanch Journal (Vol. 4, No. 2): The Secret Life of JavaServer Pages is a very good read.
An excerpt from the same,
JSP is a templating technology best-suited to the delivery of dynamic text documents in a format that is white-space agnostic.
Template text within a JSP page (which is anything that is not a dynamic element), to include all white-space and line terminators, becomes part of the final document.
All dynamic elements in a JSP are interpreted on the server and once the document is sent to the client, no further dynamic interaction is possible (short of requesting the same or another document).
If you are using JSPs, then to perform some method calles, you will have to write a servlet and then call the method in doPost or doGet method of servlet.
On the other hand, if you want to make things simpler, use JSF framework which will help you achieve your objective as JSF supports event handling.

How to insert javascript inside a java scriplet in JSP?

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?

Angular.js passing object from a jsp to the app scope

I am wondering if it is possible to pass an object using Gson (probably) from a JSP page where my app is located to the scope of my app? (In a nice way)
I want to avoid using an AJAX request to do this.
This sounds like the common pattern of inlining your data in JavaScript to avoid making an initial AJAX request.
In your JSP, you can write out the JSON into the body of an Angular service module as array or object hash data. The service module would just return this inline data and then you can make it available to the rest of your Angular app via service injection.
As Will suggested, make the JSP variable a part of the markup, the server will replace the relevant part. Psuedocode follows:
<%String contextPath=request.getContextPath();%>
<script src="<%=contextPath%>/static/js/lib/angular.v1.2.16.min.js"></script>
<script>
app.service('contextService', [function() {
this.getResourcePath = function() {
return '<%=contextPath%>/resources/' ;
};
}]);
</script>

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