Unable to get Json object in servlet? - java

I am trying to read a json object that I sent from my ajax to servlet but then I keep receiving null as the value. I tried to log the json object that I am sending from my ajax and it looks fine to me. Can someone tell me what could be my error?
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var data = $("#register").serialize().split("&");
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType:'json',
data:JSON.stringify(obj),
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out= response.getWriter();
String data = request.getParameter("obj");//this is what I get as null
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
}
The json object that I am sending
{
"apiname": "jdjdj",
"apiendpoint": "sdjsdj",
"apiversion": "djdjd",
"source": "internet"
}

Related

Java Servlet & jQuery AJAX - unable to retrieve object from session

Not sure how to solve this, need some help here.
Ajax call brings user information to servlet, I save user object in HttpSession and control goes back to Ajax from where i redirect control to next JSP page via controller servlet. However, if i try to retrieve object from HttpSession it is null .. not sure how to solve this issue.
here is my code for firstservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
here is my Javascript / AJAX code to redirect request to nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
and finally control comes to nextservlet - where i would like to process data and then show new JSP page.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
is issue because i am using -> window.location.href = result to send request to nextservlet .. and it goes to doGet??
I am not sure it but I see in Ajax
url: ‘firstservlet’,
type: 'POST'
and control goes to doGet method of nextservlet. It should be nextservlet of post method so use method doPost.
18.12.22
i'm not sure... but try it
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
18.12.26
Javascript
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
Servlet
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
It can read session attribute in doGet Method try it.

getting null `request.parts` posting files to java servlet via jQuery Ajax

here's my js code :
function sendMP3ViaAJAX(MP3File) {
console.log(MP3File.name); //file is present, as I can get its name
$.ajax({type: "POST",
url: "saveMP3",
enctype: 'multipart/form-data',
processData: false,
data: {'mp3File': MP3File},
success: function (text)
{
response = text;
},
complete: function () {
$("#retourAJAX").html("blah blah");
}
});
}
but if I debug my Project
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("MP3FILE"); //request.parts is null...
(constant CHAMP_FICHIER equals the one defined in AJAX call, i.e. mp3File ...) Do you know what's missing ? As I already have dynamically loaded content on the page, I don't want the default HTML POST submit behavior to happen...

Sending an javascript array to a servlet

Hello I have been looking at other threads like mine and I can't seem to get my code working!
I need to send the JS array containing ints to a servlet this is current code:
Javascript code:
function sendReminderEmails(){
$("#sendReminderEmails").click(function(){
var people = null;
var peopleBatch1 = null;
$.ajax({
type: "POST",
url:"getAllUnregisteredPeople",
async: false,
success: function(data){
people =JSON.parse(data);
}
});
peopleBatch1 = people.splice(0,200);
$.post("sendReminderEmails", {people:peopleBatch1, mode : "insert"} , function(data){
});
});
}
Servlet Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response){
String peopleIDs[] = request.getParameterValues("people");
}
It keeps returning null! Can someone tell me if I am doing something wrong ?
You must use JSON.stringify to send your JavaScript object as JSON string.
Change your code
var obj = { people: peopleBatch1, mode: "insert" };
$.post("sendReminderEmails",JSON.stringify(obj) , function(data) {});
On Servlet side you need you use
String jsonStr = request.getParameter("people");
then Convert this jsonStr to JSON object.
in "$ajax" you need to pass the required parameter, eg
var myArray={'john', 'paul'};
$.ajax ({
type: "POST",
url:"getAllUnregisteredPeople",
data: {people: myArray}
async: false,
success: function(data) {
people = JSON.parse(data);
}
});

AJAX error [object,Object]

this is java code ;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String,Object> hsssmap= new HashMap<String,Object>();
hsssmap.put("a","true");
hsssmap.put("b","true");
write(response,hsssmap);
}
private void write(HttpServletResponse response, Map<String,Object> hsssmap) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Gson gson = new Gson();
String json = gson.toJson(hsssmap);
response.getWriter().write(json);
}
Here is js code ;
$(document).ready(function(){
$.ajax({
url: 'uri',
type: 'POST',
dataType: 'json',
data: data,
success: function(data){
$.each (data, function (key,value) {
alert(key+" "+value);
});
},
error: function (e) {
alert("error : " + e);
}
});
return false;
});
success event doesnt work. how to fix it ?
Try to check if the page return some values or not...
try to add alert in success to check it..
try the following
$.post( "uri", function(data) {
alert( "success" + data.a + data.b );
})
if this return you data then your server side servlet working

Not able to read the JQuery data sent from Ajax in Java Servlet

Here is my Ajax code:
var email="abc#abc.com";
$.ajax({
url : "ships",
data : "{email" + email.toString() + "}",
success : function(data){
alert(data)
},
error : function(data) {
console.log("error:", data);
},
type : "post"
});
And here is my Java Servlet code:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("email"));
}
I CANNOT read data in Java Servlet The console prints out the following value for email:
null
I am using Tomcat 7
Can anyone please tell me what i am doing wrong and why i cannot read data in Java Servlet_
The property data of the param object is a JavaScript object, so to send a parameter named EmailAddress you would do:
...
url : "ships",
data : {
EmailAddress: email.toString()
},
success : function(data){
...

Categories