AJAX to call java method - java

There are many similar questions but I am not clear about one thing as mentioned below-
I have ajax call
var url = '/test/testjsp.do?param1=' + xyz;
$.ajax({
type:'GET',
dataType:'html',
url:url,
success:function (data) {
alert("Success");
}
});
which is calling an JSP page
and in that file, I am calling method from SM class
<%# page import="com.testAjax.SM" %>
<%
if (null != request.getParameter("
SM.randomMethod(request.getParameter("param1"));
}
%>
So my question is ,
I there any alternative method where I don't have to create extra Jsp file and call java method directly from Ajax call
Please help and Advise

As javascript is a client side script, it cannot invoke java methods directly which resides on the server.
To do that you have to create a web service or jsp like you did.
But I have seen vaadin gives option to call java code from javascript without writing a service or jsp. I dont know how it will help you.
https://vaadin.com/tutorials/calling-java-from-javascript
There are some concept like java adaptors and javavm to combine javascript and java try them to find it suits your need.

Related

Can I create methods in JSPs?

Can I write methods in JSPs? (Java Server Pages)
I tried writing a method within the body of the JSP, but my IDE doesn't seem to like it.
JSP can only show information to user, if you want to do some elaboration you have to re-call a servlet that to that for you.
Analize and try using this:
Everything in your jsp.
But i recommend you that if your a gonna use methods, use classes instead. They are safer and loads quite faster when calling them.
<%
//Your main logic
out.print(myMethod());
%>
<html>
your client side content
</html>
<%!
public String myMethod(){
return "Method called successfully";
}
%>

Ajax not reloading the jsp on success

Environment: IE7, jQuery 1.1 , Struts 1
Context: Making an ajax call to a Java method which, and the end, reloads the same jsp.
The steps are: jsp A -->request to java method-->doing some stuff-->ActionForward to jsp A, which is returned in the response.
Actually I'm doing this with a single request using location.href and it's working properly.
Now I need to handle multiple requests and conditions and the only way I thought was by using nested ajax calls with async:false, but that's not the point.
The problem is ajax does not reloads the jsp like location.href does.
This jsp is just a smaller part of the main jsp, so I'm not reloading the whole jsp. I guess I have to handle the response in some way, but how?
Call with location.href:
<script>
function myFunction(){
location.href = 'path/to/java/method=with_some_parameters';
}
</script>
Call with ajax:
<script>
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
//nested ajax
}
});
}
</script>
There is a similiar question:
Reload a page after jquery ajax call,
but it didn't help.
Another: How to manage a redirect request after a jQuery Ajax call, this looks better. I'm trying some things.
As I got the full html in the response ('data' in my case), It worked using
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
document.open();
document.write(data);
document.close();
//nested ajax
}
});
}
Source Replacing Entire Page Including Head Using Javascript

Call a JSF method via JS [duplicate]

This question already has an answer here:
How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?
(1 answer)
Closed 2 years ago.
i have a for loop in JS code, i want to call a method with parameters written in a JAVA managed bean that calculate a value and return a new one that will be used in the JS
Note: i'm using primefaces in the xhtml page
and handsontable to display data
that's how my js looks like
function updateMoneyValue(){
var thetable; //the handsonTable
for (var i =0 ; i < thetable.length ; i++)
{
var myNewValue = theBeanMethod (firstParam , secondParam);
}
}
You can use PrimeFaces remote command component (<p:remoteCommand>).
RemoteCommand enables executing backing bean methods and do partial
update triggered by custom client side script. This example
demonstrates a use case where a certain part of a page can be lazily
loaded on demand.
Add it to the view it in a following way:
<p:remoteCommand name="myRemote" actionListener="#{myBean.listen}"/>
And use it in Javascript like so:
<script type="text/javascript">
myRemote(); //makes a remote call
</script>
or call it from an event handler like so:
<div onclick="myremote();">...</div>
If you additionally want to pass parameters to the server make a following call:
<script type="text/javascript">
myRemote([{name:'param1', value:150}, {name:'param2', value:220}]); //makes a remote call with parameters
</script>
The listener could be like:
public void listen(){
FacesContext context = FacesContext.getCurrentInstance();
Map<String,String> params = context.getExternalContext().getRequestParameterMap();
System.out.println(params.get("param1"));
System.out.println(params.get("param2"));
}
you can use primefaces remoteCommand component. you can find details about remoteCommand in this blog post.
http://blogs.bytecode.com.au/glen/2013/09/25/calling-primefaces-remotecommand-with-javascript-arguments.html
There's no way to do that directly.
Your java/jsf code is parsed and executed on server and then sent to client (browser). Only in browser javascript starts executing.
If you want to call some bean's method and get the result from client/javascript, you need to initiate new network request via AJAX call or somewhat. Also you can try to rework the logic of your application.

Passing json object via ajax from jsp to javascript

How can pass json values from jsp to javascript as object via ajax?
I can not use global js variables in jsp because this will lead to json content to be visible in page's source
Here is the scenario that I want to achieve:
url of jsp is opened in browser.
Data is being created in scriptlet and coverted to JSON format
json is "sent" to javascript as object
From above scenario, i understand that javascript must initiate the ajax call to jsp.
The issue with this, that jsp's code will be invoked 2 times:
When page is opened in browser - data is prepared
on each ajax call same code will be called again
Constrains: No jquery, no other libs, no servlets, no additional jsps. :(
EDIT:
There is additional problem, I need to pass multiple json objects to javascript.
I wont be able to do it with response.getWriter().write();
I don't think concatenating all json objects and sending is the correct solution.
The parsing of the received object in javascript http.responseText will be overwhelming.
Why do you need ajax here? If you know that you need to populate some things from server onto jsp page you can do that through scriplets itself:
EX
<%# page import="com.mypackage.PersonDAO" %>
<html>
<body>
<table>
<th>Name</th><th>Email</th><th>Contact</th>
<%
List<Person> myList = PersonDAO.getAllPersons();
for(Person person:myList)
{
%>
<tr>
<td><%=person.getName()%></td>
<td><%=person.getEmail()%></td>
<td><%=person.getContact()%></td>
</tr>
<%}%>
</table>
</body>
</html>
This is a very simple example. You can do more complex things using JSTL.. :)
So there is no jquery, no Servlets, no ajax and no extra jsp's :)
UPDATE
Since you want data in your javascript before page loads you can use jQuery's holdReady() method.
$.holdReady( true );
$.get( url, function() {
// Perform something
$.holdReady( false );
});
See but all modern browsers have developer tools like firebug for mozilla, so any ajax call made will be trapped by them. The only way you can secure them is my encrypting them.. which will complicate things for you... IF you can explain the scenario you are trying to implement may be I can come up with it..

Call from one JSP file to another JSP

I need to call from one JSP to another, do some stuff over there..
I am inside the caller jsp, inside his handleReqeust(HttpServletReqeust request)
method I am trying to forward the request to another JSP, to call the other JSP file to his handleRequest(HttpServletReqeust request) off course with the request object
I tried it:
RequestDispatcher dispatcher = request.getRequestDispatcher("/theSecondJspFile.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
but to make it work I need for it the object response, but I don't have it,
I am sure I missed something basic, but what?
From my question you can see, I don't have solid backround in java, so please correct me, or refer me to good guide if you feel it necessary
Thanks.
-------------------Edit--------------------------------------
I don't need a redirect, I just want to call another JSP file to his handleRequest method
I think it relate to HTML
What I can make out of your question is that you need to redirect to a secondpage.html from firstpage.html with some data. You can use both GET or POST method to send the data.
For the GET method just redirect to secondpage,html?data=value. The data will be available in the HttpRequest parameter in the controller of the secondpage.html where it can be used as required.
For the POST method you would need to post the data (using a form on firstpage.html) to secondpage.html. In the controller of the secondpage.html the data should be available in a similar way as before.
To include another JSP in a jsp :
<jsp:include page="foo.jsp"/>
You can find some reference material here.
I can not be sure, but what I think you are trying to do is to include a jsp page on to your jsp page and use the the objects and other variables declared in the first jsp page in your second.
<%# include file="mypage.jsp" %> should help you do this.
If this is not what you are looking for, please make your question tad bit more clear. some code will help really.
JSPs are supposed to be used to present the final result. JSPs are not supposed to be part of business tasks leading to this result. There you use normal Java classes for, starting with a servlet class. Let the HTTP request (the one which you enter in browser address bar or specify in some HTML link or form) point to the URL of the servlet instead. This way you can write Java code in the servlet the usual way to invoke other Java classes/methods and finally forward the request to a certain JSP file based on the outcome of the result and then just let that JSP present the final result.
To start with servlets, I'd suggest to read our Servlets info page.
I just added empty Iframe, and set his URL when I needed to call him

Categories