I know it is a simple one . But couldn't find a solution.
My jQuery-ajax will be ,
var json = {"message":"Message123","time":"time123","name":"test123"}
data : JSON.stringify(json),
My Spring controller will be ,
#RequestMapping(value = "chat.html", method=RequestMethod.GET )
public #ResponseBody String getChat() {
System.out.println("Entered in to the controller ");
String name == ???
String msg == ???
String time == ???
//Process the functionality using the msg,name,time
return "Json String";
}
How can I get the values of the name, message , time.
Hope our stack members will help me.
var json = {"message":"Message123","time":"time123","name":"test123"}
data : JSON.stringify(json) should have a key ,
data : {json:{"message":"Message123","time":"time123","name":"test123"}},
url:/json/test
Controller
#RequestMapping(value = {"json/test"},method = RequestMethod.GET)
#ResponseBody
public String jsonTest(String json){
JSONObject jsonObject = JSONObject.fromObject(json);
String m = jsonObject.get("message").toString();
String t = jsonObject.get("time").toString();
String n = jsonObject.get("name").toString();
}
I use the net.sf.json.JSONObject
You can use org.Json jar from this link ...
Then try this code, I have done is in my current project and is working fine and efficiently
var json = {"message":"Message123","time":"time123","name":"test123"}
$.ajax({
type: "POST",
url: "/chat.html",
data: "jsonObject="+json,
success: function(response) {
// your success code
},
error: function(e) {
// your error code
}
});
In controller change your code like this
#RequestMapping(value = "/chat.html", method=RequestMethod.POST )
public #ResponseBody String getChat(HttpServletRequest req,HttpServletResponse res) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(req.getParameter("jsonObject"));
} catch(JSONException _instance) {
// Exception Handle Message
}
System.out.println("Entered in to the controller ");
String name ="" , msg = "", time = "";
if(jsonObject.has("name")) {
name = jsonObject.getString("name");
}
... // Do it for other variables also
//Process the functionality using the msg,name,time
return "Json String";
}
Related
I am trying to send a Json string along with multiple files into my Spring Controller, however it would always give me a 405 Method Not Allowed Error, what am I doing wrong?
Javascript Code:
var formdata = new FormData();
formdata.append('user', JSON.stringify(userData));
files.forEach(file=> {
formdata.append('files', file);
});
jQuery.ajax({
url: "user/submitForm",
type: "POST",
data: formdata,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function (data)
{
console.log("SUCCESS");
},
error: function (request, status, error) {
alert(status + " : " + JSON.stringify(request));
}
});
Controller in Spring:
#PostMapping(value= "/submitForm", consumes = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> userRegistration( #RequestPart("user") String user,
#RequestPart("files") List<MultipartFile> files, BindingResult bindingResult) {
ObjectMapper obj = new ObjectMapper();
User newUser = new User();
newUser = obj.readValue(user, User.class);
System.out.println("User : \n"+ newUser.toString());
System.out.println("Files : \n"+ files.toString());
return null;
}
This was the solution that I found from Antonio112009's answer
SOLUTION
#PostMapping(value = "/submitForm")
public ResponseEntity<?> userRegistration(
#RequestParam("user") String user,
#RequestParam(value = "files", required = false) List<MultipartFile> files) {
ObjectMapper obj = new ObjectMapper();
User userObj = new User();
.
.
.
}
I use another solution, who works as expected and are a bit more flexible from my point of view.
Front-end part is in Typescript.
Front-end
var formData = new FormData();
options.files.forEach(function (file) {
formData.append(file.name, file);
});
formData.append("myParam", "coucou");
var xhr = new XMLHttpRequest();
xhr.open("POST", "/rest/upload");
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
options.callback("success", options.files.map(function (file) {
return {
file: file,
content: data[file.name]
};
}));
};
xhr.send(formData);
Back-end (Java Spring)
#RestController
#RequestMapping(value = "/rest")
public class UploadController {
#PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Boolean> upload(MultipartHttpServletRequest request) {
// Get param
Object myParam = request.getParameter("myParam");
// Get iteretaor on all files
Iterator<String> iterator = request.getFileNames();
MultipartFile multipartFile = null;
while (iterator.hasNext()) {
multipartFile = request.getFile(iterator.next());
final String fileName = multipartFile.getOriginalFilename();
final String fileSize = String.valueOf(multipartFile.getSize());
// Add logic ....
}
}
return new ResponseEntity(true);
}
Hi there I am using jQuery with Spring MVC to get the book_id from the database but I am getting error alert every time
I have used jQuery ajax() method and defined all the parameters properly like url and in Controller i have used all proper annotations but failed to get the output.
$(document).ready(function () {
$("#bookId").keypress(function () {
var bookid = $(this).val();
alert($(this).val());
$.ajax({
url: "getBookQuantity.htm",
data: {
bookid : bookid
},
dataType: "json",
success: function (json) {
if (json !== null) {
alert(json);
}
},
error: function (e) {
alert("Some error occured while getting book id list");
}
});
});
});
Controller code:
#RequestMapping(value = "/getBookQuantity.htm")
#ResponseBody
public String getBookQuantity(#RequestParam(value = "bookid", defaultValue = "0") int bookid) {
System.out.println("bookid======="+bookid);
int quantity = this.bookService.checkBookQuantity(bookid);
String json = null;
Gson gson = new Gson();
json = gson.toJson(quantity);
return json;
}
Getting error alert every time
I am new to java, i am trying to pass two json objects from ajax call to controller class... but i am getting below exception
Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.controllers.EmployeeController.saveData(java.lang.String,com.entities.EmployeeData,org.springframework.validation.BindingResult)
Jquery Code:
$("#saveData").submit(function(event) {
var data = [];
var formData = {};
var myJsonString;
var slab, lower;
$("table tbody tr").each(function(index) {
//alert(index);
slab = $(this).find('.slab').val();
lower = $(this).find('.lower').val();
if(slab != undefined && lower != undefined){
var form1 =new Object();
form1.slab=slab;
form1.lower=lower;
data.push(form1);
}
});
var form = this;
event.preventDefault();
$.each(this, function(i, v){
var input = $(v);
formData[input.attr("name")] = input.val();
});
var url = "/Portal/SaveData";
ajaxCall(url,formData,data);
});
function ajaxCall(url,formData,data){
//alert("AjaxPost!!!"+url);
// DO POST
$.ajax({
type : "POST",
contentType : "application/json",
url : url,
data : JSON.stringify({formData:formData,value:data}),
dataType : 'json',
beforeSend: beforeSendHandler,
success : function(response) {
alert("Success");
}else{
alert("else");
}
},
error : function(e) {
bootbox.alert({
size: "small",
title: "ALERT",
message: "There seems to be some problem while Proccessing record!"
})
}
});
}
Controller Method:
#RequestMapping(value = "/SaveData", method = RequestMethod.POST)
public #ResponseBody String saveData(#RequestBody String value,#Valid #RequestBody EmployeeData emp, BindingResult result) {
System.out.println(" Creating!!!");
//logic here
}
Where is the mistake in ajax call or in controller file?
there is any other way to pass multiple json objects to controller class file?
The #RequestBody annotation is expected to map to one and only one parameter in your method and to contain the entire contents of the incoming request.
You should map all your form data into a single JSON object, then handle that as a single JSON object in the backend as well.
Can Anyone help me on this, i m trying to convert complex json object send through ajax into a object. so that i can use this object to pass into my model.
The JSP code is:
function callRemovefilter()
{
var jsonObjects = {
address1: "Address_1",
city: "City",
pin: "PIN"
};
var jsonObjects2 = {
locality:"Loc1",
shippingType:"Regular",
shippingCost:20
};
var cust= JSON.stringify(jsonObjects);
var sales=JSON.stringify(jsonObjects2);
jQuery.ajax({
url: "http://localhost:8080/OnlineStore/kmsg/grocery/SaveSalesOrder",
type: "GET",
data: {CustomerInfo:cust,SalesModel:sales},
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
//Write your code here
}
});
}
// The controller code is
#RequestMapping(value = "/SaveSalesOrder", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody String SaveCustomerOrder(#RequestParam Map<String,String> requestParams) throws Exception
{
ObjectMapper objectMapper = new ObjectMapper();
SalesCommandObject salesCommandObject= new SalesCommandObject();
salesCommandObject = objectMapper.readValue(body, SalesCommandObject .class);
return "Success";
}
// Code of JSP to send object to controller
var salesCommandObject = {}; salesCommandObject.CustomerInfo =
{
"address1": "Address_1",
"city": "City",
"pin": "PIN"
};
salesCommandObject.SalesModel =
{
"locality":'Loc1',
"shippingType":'Regular',
"shippingCost":20
};
$.ajax
({
type: "POST",
dataType : 'json',
async : true,
url: "http://localhost:8080/OnlineStore/kmsg/grocery/SaveSalesOrder",
data : JSON.stringify(salesCommandObject),
}).done(function(data,type,xml)
{
console.log(data);
}).fail(function()
{
alert("Something Bad Happened, Service failed");
})
Send objects, not jsonstrigs. And in controller in your method SaveCustomerOrder get an object, not Map, like:
#RequestMapping(value = "/SaveSalesOrder", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody String SaveCustomerOrder(#RequestParam CustomerInfo ci, #RequestParam SalesModel sm) throws Exception
{
//your logic here
return "Success";
}
And add getters and setters to appropriate classes(i.e CustomerInfo, SalesModel) like:
`public class SalesModel{
private String sale_id;//or whatever field or property you need
public String getSale_Id() {
return sale_id;
}
public void setSale_Id(String si) {
this.sale_id = si;
}
}`
#RequestMapping( method = RequestMethod.POST, value = DataController.RESOURCE_PATH + "/file", headers = "content-type=application/json" )
#ResponseBody
public void export( #RequestBody JSONObject json, HttpServletResponse response ) throws IOException
{
String myString = "Hello";
}
The string is generated inside the Controller.
What I want is to send back to the user a Window where he can save a file which contains the myString.
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(createJSON()),
contentType: "application/json",
success: function(response)
{
console.log("Exported JSON: " + JSON.stringify(createJSON()));
console.log(response);
},
error: function()
{
console.log(arguments);
alert("Export process failed.");
}
});
It clearly doesn't work in this current state and I am stuck at the moment.
here is a sample:
#RequestMapping( method = RequestMethod.POST,
value = DataController.RESOURCE_PATH + "/file",
headers = "content-type=application/json" )
public void export( #RequestBody JSONObject json, HttpServletResponse response )
throws IOException {
String myString = "Hello";
response.setContentType("text/plain");
response.setHeader("Content-Disposition","attachment;filename=myFile.txt");
ServletOutputStream out = response.getOutputStream();
out.println(myString);
out.flush();
out.close();
}
PS: don't forget to put some random stuff in your url (as parameter for example) to ensure your browser does not cache the text file.
To return a file you need to use the MediaType.APPLICATION_OCTET_STREAM as the response type.
I recommend using filesaver.js.
Then your solution will look like:
var text = JSON.stringify(createJSON());
var blob = new Blob([text], {type: "text/plain; charset=utf-8"});
saveAs(blob, "myfile.txt");