read jquery data send from AJAX to java servlet - java

Here is my AJAX code which triggers the Servlet 'CalculateLace'
laceTd.dblclick(function() {
var jsonObj= { jsonObj: [ {"rowID": $(nRow).attr('id')} ]};
$.ajax({
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
traditional: true,
url: "CalculateLace"
});
});
And here is my Java Servlet code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String id = req.getParameter("rowId");
//do something
}
But I keep getting String id as null. I also tried
String id = req.getParameter("id");
but to no avail. What am I doing wrong here?

Try this way -
var jsonObj= {"rowId": $(nRow).attr('id')};
and get rowID in your servlet this way - You can get library to parse your json here JSON.org
req.getParameter("rowId");

Related

How to retrieve parameters from POST in XPages (java)

I want to use Domino as a backend, and html/jquery as a frontend for my web application. So I have:
$.ajax({
type: 'POST',
url: 'mydb.nsf/xpage.xsp',
contentType: 'application/json; charset=utf-8',
data: {
f1: "hello",
f2: "hello again"
},
success: function (response) {
console.log("SUCCESS");
},
error: function (error) {
console.log(error);
}
});
In Domino:
public static String doGet(HttpServletRequest req, HttpServletResponse res) throws JsonException, IOException, NotesException {
return doPost(req, res);
}
public static String doPost(HttpServletRequest req, HttpServletResponse res) throws JsonException, IOException, NotesException {
System.out.println("1) "+req.getAttribute("f1"));
System.out.println("2) "+req.getParameter("f1"));
System.out.println("3) "+req.getContentLength());
return "AllOK";
}
In firebug and domino log I see that POST goes trough ok, gets the response. But I can't figure out how to get params f1 and f2 in domino.
In domino log:
1) is null,
2) is null,
3) is 23.
Idea for later is to POST JSON, but for now it would be great to have this code working.
How to get POST parameters in domino via java?
(I see stackoverflow has a lot of similar questions answered, but couldn't find anything specific to my problem)
Thank you!
Use reg.getReader() or req.getInputStream() to read the body of the request with elements f1 and f2.
Here is an example how you can read the JSON data:
https://stackoverflow.com/a/3831791/2065611
req.getParameter() works only if content type is "application/x-www-form-urlencoded", not json.

How to send and catch parameter from JavaScript (AJAX request) to Servlet

I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.
I searched how to do it on Ajax and according to:
How to send parameter to a servlet using Ajax Call
I used: url: "InformationServlet?param=numberOfPlayers"
But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
you can see that the attributes size is zero
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
Engine engine = (Engine)getServletContext().getAttribute("engine");
String responseJson = "";
if(request.getAttribute("numberOfPlayers") != null)
{
String numberOfPlayers = "";
numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
responseJson = numberOfPlayers;
}
out.print(responseJson);
} finally {
out.close();
}
}
JavaScript (AJAX request):
function getNumberOfPlayersAndPrintSoldiers()
{
$.ajax({
url: "InformationServlet?param=numberOfPlayers",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(numberOfPlayers) {
var r = numberOfPlayers;
}
});
}
Edit:
you probably want to use getParameter and not getAttribute
Moreover, please pay attention to the order of parameter name and his value:
request.getParameter("param");
instad of:
request.getParameter("numberOfPlayers");
because the url form contains parameter name first and then the parameter value. for example:
myurl.html?param=17
and if more parameters needed then use the separator & sign
myurl.html?firstName=bob&age=5

Handle JSON Array posted from Ajax in Struts 1.3

I build the JSON Object like this:
var key = //some calculated key
var key = //some calculated value
var list = {item: []};
list.item.push({
"key" : key,
"value" : value
});
Then I send the array like this:
sendData = function() {
$.ajax({
url :'<html:rewrite action="/sendData"/>',
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {"list":list.item},
success:function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
How can I retrieve in my action the JSONArray/JSONObject and handle it?
I've tried this:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String list = request.getParameter("list"); //null, I supposed to find a string formatted like json
return null;
}
Even GSON library is allowed!
You will get significant improvement if you convert your object to string when sending it as parameter.
data : {list: JSON.stringify(list.item)}

Can't receive response from servlet in Jsp file

I am trying to send some query from jsp file to servlet via post method and then get some modified result from servlet to jsp file.
I am able to complete first part successfully, but I cannot receive the response in jsp file.
Servlet post method is:-
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONObject js = <some method to get json>;
System.out.println(js); //works fine
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(js.toJSONString());
}
And my jsp code is:
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + response);
});
}
</script>
The output is:
How can i get that json string ?
you are getting json as response need to stringify it.
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + JSON.stringify(response));
});
}
</script>

Passing custom objects from servlet to Jquery

i have a servlet my goal is to return a customer object from the process request, where i can then access this object in my jquery. Does anyone know how i can go about doing this?
e.g. myObject.getMethod()
Servlet Code:
Customer loginResult;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
//request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
out.println(loginResult);
} finally {
out.close();
}
}
JSP CODE:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "get",
data: dataf,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
Can someone please assist me in resolving this issue, thank you for your help in advance.
Since you want to handle an ajax request using a Servlet, the best bet you have is writing the data of your custom object into the response. The easier way I found to accomplish this is using JSON. There are lot of libraries that handles JSON conversion from objects to Strings and vice versa, I recommend using Jackson. This is how your code should look like.
Servlet code:
import com.fasterxml.jackson.databind.ObjectMapper;
#WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {
//Jackson class that handles JSON marshalling
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
//login operation should be handled in POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer loginResult = ...; //process data and get the loginResult instance
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//marshalling the data of your loginResult in JSON format
String json = OBJECT_MAPPER.writeValueAsString(loginResult);
response.getWriter().write(json);
}
}
Javascript code:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "post", //login action MUST be post, NEVER a get
data: dataf,
success: function(data) {
//shows the relevant data of your login result object in json format
alert(data);
//parsing your data into a JavaScript variable
var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
//now you can use the attributes of your loginResult easily in JavaScript
//for example, assuming you have a name attribute in your Customer class
alert(loginResult.name);
}
});
return false;
});
});
</script>
More info:
How to use Servlets and Ajax?
Parse JSON in JavaScript?

Categories

Resources