Get json data server side in java web application - java

i have trying to make ajax call with json and below is my code discription
$(document).ajaxStart(function () {
$("#innerpanel").html("<img class='test' src='Image/ajax-loader_clock.gif' alt='loading...' />");});
/* $("#loader").ajaxStop(function () {
$(this).hide();
}); */
$('#btn').click(function(){
testService();
});
function testService(){
name=$("#name").val();
password=$("#password").val();
var testData={name : name,password : password};
$.ajax({
type: "post",
url: "login.do",
data:testData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("madhav");
$("#innerpanel").html("<p1>Welcome</p1> </br>"+"<p1>"+msg.name+"</p1></br><p1> and Your password is "+msg.password+"</p1>");
/* document.writeln("Book id: " + msg.name); */
}
});
}
});
and sever side code is
String userName=request.getParameter("name");
String password=request.getParameter("password");
PrintWriter writer = response.getWriter();
JSONObject obj=new JSONObject();
obj.put("name", userName);
obj.put("password",password);
writer.print(obj);
writer.flush();
But i get null value for both username and password .please help me with example how can I get name and password server side.
if i remove code from request
contentType: "application/json; charset=utf-8",
dataType: "json",
i get name and password value with above server side code.
but how can i do it without removing
contentType: "application/json; charset=utf-8",
dataType: "json",

var testData = {"name" : name, "password" : password};

Related

Error javax.json.stream.JsonParsingException: when making an AJAX API call

I have developed a web based program using java jersey in my back end and jsp in my front end. When I make a post API call using Ajax my back end gets the following exception.
javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)
I guess it's something wrong with the data which I'm passing through the Ajax API call.
Here is my ajax API call:
var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: obj,
dataType: 'json',
success: function () {
alert("successed");
}
});
This is my back end implemented code:
#Path("testing")
public class test {
UserRepository userRepo=new UserRepository();
#Path("users")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
userRepo.createUser(a);
return a;
}
}
You should send the data as a JSON String, not a JSON Object. Avoid the JSON.parse from your code.
var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';
Alternatively, I would construct the JS Object, and apply JSON.stringify on it. This way, the code is more readable:
var data = {
userName: "John",
password: "hgvv",
img: "New York",
fname: "kjbjk",
lname: "bkbkkj",
tp: "buhb",
address: "jhbjhb",
type: "user"
};
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: JSON.stringify(data), // added JSON.stringify here
dataType: 'json',
success: function () {
alert("successed");
}
});

Send json object with another parmeter to the controller in spring mvc

1.- I want to recive this two paramters like this in my controller :
*/Controller
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST)
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
String table_name = tableName;
String catalogInserted = catalogGenericService.insertCatalogGeneric( table_name, catalogGeneric);
return catalogInserted;
}
2.- I send to the contoller in this way...
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: {'catalogGeneric' : JSON.stringify(description_data) , 'tableName' : "fadsf"},
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
3.- In my debug I receive error 400 not found the direction .... i know that is for the way that i send the parameters , but what will be the correct form to do that ?
In your case, Ajax call having contentType: "application/json" format, So when your doing ajax call with JSON format, In your Controller your Request Mapping should have consumes = "application/json",
For the particular request mapping add like this in your controller,
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST,
consumes = "application/json")
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
[Additional]
For safe request body format
try to stringify the whole JavaScript Object.
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: JSON.stringify({'catalogGeneric' : description_data , 'tableName' : "fadsf"}),
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
}
});

sending json data from javascript to java

I'm trying to send json data to servlet using ajax jquery call... below is the code
$(function() {
$( "#mybutton").click(function() {
var testdata = JSON.stringify({
'name': 'name',
'desc':'test'
});
$.ajax({
type: "POST",
url:"/Alert/ReportServlet",
data: testdata,
dataType: "json",
contentType: "application/json",
success : function(data){
console.log("success:", data);
},
error : function(data) {
console.log("error:", data);
}
});
});
});
and the servlet code is
public class ReportingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
System.out.println("The data is" + request.getParameter("testdata"));
}
}
The value is coming as null...Please suggest
In servlet try with
request.getParameter("name");
request.getParameter("dest");
In your Ajax call do something like this
$(function() {
$( "#mybutton").click(function() {
var testdata = JSON.stringify({
'name': 'name',
'desc':'test'
});
$.ajax({
type: "POST",
url:"/Alert/ReportServlet",
data: { d : testdata },
dataType: "json",
contentType: "application/json",
success : function(data){
console.log("success:", data);
},
error : function(data) {
console.log("error:", data);
}
});
});
});
then in java try :
request.getParameter("d");
this you can use some library (like jackson) to convert d into HashMap

JSON Error in retrieving data

Here is Client side code:
function startAjax() {
$.ajax({
type : 'GET',
url : 'customers/ShowAllCustomers',//this is url mapping for controller
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
success : function(response) {
alert(response.get(0).first_name);
//this response is list of object commming from server
},
error : function() {
alert("opps error occured");
}
});
}
and here is my Controller:
#RequestMapping(value="/ShowAllCustomers", method = RequestMethod.GET)
public #ResponseBody List<Customer> AllCustomersList() {
List<Customer> customers= customerService.getAllCustomers();
return customers;
}
Everytime "oops error occured" alert appears. Can you please point out error in this for me. I will be really thankful......
List<Customer> customers= customerService.getAllCustomers();
return customers;
The above code returns a Java List , but the jQuery is expecting a JSON String .
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
You need to convert the List to a JSON string using some JSON library.

Ajax request for login not working using $.post() method in jquery

I have a login form i want to send username password to servlet and returning response from there but my username and password is not even going to servlet i have searched a lot but not getting anything please help me out ..
my code is given belo :
<script type="text/javascript">
$(document).ready(function () {
$(".mloginform").submit(function () {
var uName = $("#usernameInputField").val();
var passwd = $("#passwordInputField").val();
$.post("/LoginServlet", {
username: uName,
password: passwd
}, function (data) {
if (data.success) {
alert("hello");
}
}, 'json');
return false;
});
});
</script>
Inside LoginServlet doPost method:
String userName=request.getParameter("username");
String passwd=request.getParameter("password");
Gson gSon=new Gson();
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", true);
JsonObject myJson=new JsonObject();
myJson.add("data", gSon.toJsonTree(data));
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.write(myJson.toString());
where I am wrong.
$(document).ready(function () {
var uName = $("#usernameInputField").val();
var passwd = $("#passwordInputField").val();
var params={username:uName,password:passwd};
$.ajax({
url : "LoginServlet",
type : "post",
cache : false,
async : false,
dataType : "json",
data : params,
contentType : "application/json; charset=utf-8",
success : function(data) {
alert("hello");
}
});
});

Categories