Reputation: 565
I have a webpage which shows some info. In my webpage I have many coordenates (lon, lat) and I want to make a java class to ordenate these coords.
Which I am trying to do is before showing coords, send them to the java servlet. This servlet would ordenate them and send back to the webpage to show them.
I want that webpage doesn't refresh so I think I need ajax to call servlet, I have it more or less under control. But I don't know how to receive data in java from a webpage.
I created some servlets in past but always calling java function using javascript. The problem of doing it by this way is that web browser goes to other webpage (jsp with java calls).
I don't have yet the code for ordering coords but I am using this to try:
package ordenacion;
public class OrdenarListaPuntos {
public static String ordenar(String cadenaDesordenada){ //String unordered
String cadenaOrdenada;
//here goes the code for ordering
cadenaOrdenada = cadenaDesordenada;
return cadenaOrdenada; //String ordered
}
}
I just know how to call java function from javascript using jsp but not from other webpages in other servers or without refreshing webpage...
Do you have any idea about how I should do it? Or what I should read about it?
Upvotes: 1
Views: 6652
Reputation: 373
You need to do a bit of reading, as you are trying to grasp more than just a simple concept. Take a look at these for a start;
How do you send an array as part of an (jquery) ajax request
http://codesstore.blogspot.co.uk/2011/12/json-with-jquery-jsp-servlets.html
http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/
http://srikanthtechnologies.com/blog/java/jobs_employees_jquery.html
In the end you are going to use this basic structure. You are going to use a POST instead of the GET that I mentioned in here
var valSend = "aSingleParam";
var url = "/yourApplicationWebContext?paramPassed="+valSend;
console.log(url);
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
console.log("Data returned : " + data);
if (typeof data == 'object') {
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("jqXHR : "+jqXHR + " text status : " + textStatus + " error : " + errorThrown);
}
});
Java Servlet Side.......
Your web.xml will have a servlet and corresponding servlet mapping;
//Your Java Servlet class
package com.xyz;
public class ServlvetClassName extends HttpServlet {
//The type: "GET" in the ajax call will trigget a "get" which the doGet will handle
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
if(null!= req.getParameter("paramPassed")){
// get and use your parameter, which "is paramPassed".....
}
}
//The type: "POST" in the ajax call will trigget a "post" which the doPost will handle
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
Upvotes: 4