Spring 3.1, JSON response ModelAndView - java

This is my first post. I'm sorry for my english...
I have problem with postJSON and returning partial view with ModelAndView.
My controller:
#RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")
public #ResponseBody ModelAndView addSubMenu(#RequestBody Menu menu) {
ModelAndView mav = new ModelAndView(PathConfig.MENU_DIR + "show_url");
int id = menuService.saveOrUpdateMenu(1, menu.getTitle(), menu.getUrl(), 4, "pl");
mav.addObject("submenu", menuService.get(id));
return mav;
}
My ajax code:
$("#menuUrl").submit(function(){
var menu = $(this).serializeObject();
$.ajax({
type: "POST",
url: config.resourcePath+"/addUrl.html",
data: JSON.stringify(menu),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(response){
$( "#site" ).append(response);
},
error: function(e){
alert("Server did not response.");
}
});
});
But... I have error: Server did not response...
How I can render partial view with json?
Thanks.

There are a few things which could be wrong here:
By specifying a Content-type header of application/json you are expecting a response of json back, however looking at the way you are handling the response it looks like what you want is an html
if it is html that you are looking for as a response then remove the Content-Type header from the request, remove the #ResponseBody annotation from ModelAndView response , instead just return a view which points to a normal jsp which can create the html response that you are expecting..
#RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")
public ModelAndView addSubMenu(#RequestBody Menu menu) {
...
}

If what you want is json to update some parts of the page don't return a ModelAndView, return String, make sure to have a json serializer
#RequestMapping(method=RequestMethod.POST, value = "/addUrl.html")
public #ResponseBody String addSubMenu() {
//yourvariable
return yourvariable.toString();
}

$("#menuUrl").submit(function(){
var obj = $(this).serializeObject();
obj.parentId = getParentId(menuDivId);
$.ajax({
url: config.resourcePath+"/addUrl.html",
data : JSON.stringify(obj),
contentType : 'application/json',
type : 'POST',
context: document.body,
}).done(function(response) {
$("#site").append(response);
});
return false;
});
And controller returning ModelAndView.
It's working.

Related

Axios. Spring MVC returns a 415 response

I am using Vue.js, axios and Spring.
On the page I have the following axios code
axios({
method: 'post',
url: '/user/info',
params: {
'_csrf' : document.getElementById('csrf_id').value,
'name' : 'job',
'age' : '25',
},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
And on the server I have a receiving method like this
#Controller
#RequestMapping("/user")
public class UserInfo {
#ResponseBody
#PostMapping(value = "/info", consumes = "application/x-www-form-urlencoded", produces = "application/json" + ";charset=utf8")
public String info(#RequestParam(value = "name") String name, #RequestParam(value = "age") String age) {
System.out.println(name);
System.out.println(age);
return "ok";
}
}
Axios makes a request to the server, but the server returns a 415 response.
The request headers are missing the application/x-www-form-urlencoded content type. I suspect the problem lies precisely in this.
Tell me, what am I doing wrong?
HttpMethod Post is a method of writing and transmitting data in the request body.
In your case, you put data through params. If you execute code as you write, data will be sent such as /user/info?_csrf=value&name=job&age=25 and there will be no data in the request body.
To get the response you want, you can modify it as below.
axios({
method: 'post',
url: '/user/info',
data: '_csrf=csrf&name=job&age=25',
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
change params keyword to data and write data like querystring.

Response entity is not returned after ajax call, why?

Here I try to make a simple post request to my controller with an url as post body. After ajax call completes, I don't receive the response from the controller. Why ?
This is my controller:
#RestController
public class Controller {
#RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = {"application/json"})
public ResponseEntity<String> authenticate(#RequestBody String url) {
System.out.println(url);
return new ResponseEntity<>("TOKEN", HttpStatus.OK);
}
}
And the ajax call:
var url = 'https://slack.com/api/oauth.access' +
'&client_id=' + client_id + '&client_secret=' + client_secret + '&code=' + code + '&redirect_uri=' + redirect_uri;
$.ajax({
url: "/authenticate",
type: 'POST',
data: JSON.stringify(url),
contentType: 'application/json',
dataType: 'json'
}).done(function (data) {
console.log(data);
})
Nothing is printed in the console. Can you tell me what the problem is please ?
It turns out that the string that I return from the controller cannot be parsed to json because it doesn't have a valid format
I changed the line
return new ResponseEntity<>("TOKEN", HttpStatus.OK);
to
return new ResponseEntity<>("\"TOKEN\"", HttpStatus.OK);
And it works fine.
Return JSON for ResponseEntity<String>
#Gustavo
Hi, have you tried JSON view?
JSON always returns a key value; by which we can access elements.
Mostly the key value is suffix with 'Result' along with Funcation name.
If your looking at JSON.stringfy("..") is used to just check if data received is correct, after hat you need to paese J
var text = JSON.parse(response.data.GetAllDataResult);

Multiple ajax data to Spring MVC controller

I need to send data to Spring MVC controller by ajax. But controller doesn't work if I send more than one parameter.
Controller method:
#Timed
#RequestMapping(value = "saveee", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
With this ajax code all works perfectly:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
But if I change data parameters, then controller doesn't get request even.
data: ({'fieldBean': JSON.stringify(fieldBean.data), 'id': id})
What I'm doing wrong?
That won't work. First lets clarify the difference between #RequestBody and #RequestParam.
The #RequestBody method parameter annotation should bind the json value in the HTTP request body to the java object by using a HttpMessageConverter. HttpMessageConverter is responsible for converting the HTTP request message to an assoicated java object. Source
And Use the #RequestParam annotation to bind request parameters to a method parameter in your controller. Source
Coming to you question...
With first ajax request you are sending JSON to your controller not request parameters, so #RequestBody is OK.
In the second ajax request also you are sending JSON but with two fields (fieldBean and id). Since #RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object. You should modify the Java Object(ie TicketTemplateFieldBean) to hold id field also. This will work if you have only one argument in the controller.
Then, how to have second argument?
You cannot use two #RequestBody like :
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, #RequestBody Long id).
as it can bind to a single object only (the body can be consumed only once), You cannot pass multiple separate JSON objects to a Spring controller. Instead you must Wrap it in a Single Object.
So your solution is to pass it as Request parameter- #RequestParam, or as a path variable - #PathVariable. Since #RequestParam and #ModelAttribute only work when data is submitted as request parameters. You should change your code like this:
#Timed
#RequestMapping(value = "saveee", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, #RequestParam("id") Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
And change you request URL as follows:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee?id=10',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
You can use #PathVariable like this:
#Timed
#RequestMapping(value = "saveee/{id}", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, #PathVariable("id") Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
And change you request URL as follows:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee/10',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
To convert parameter to the method arguments you have to use #RequestParam, so the code should be modified like this:
Controller :
#Timed
#RequestMapping(value = "saveee", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestParam TicketTemplateFieldBean fieldBean, #RequestParam Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
You're not passing valid data to the controller. Try something like this.
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee',
data: JSON.stringify({
fieldBean: JSON.stringify(fieldBean.data),
id: id
}),
success: function(result) {
//TODO
}
})

can not able to call spring controller using ajax

I am trying to call a spring controller using ajax, but can not able to go to the controller. I am getting Error 405 Request method 'POST' not supported error. I am keeping my code here please give suggestion to come over it
this is my ajax code calling controller from jsp page, here i am getting the anchor attribute value.
basic.jsp
function organizationData(anchor) {
var value = anchor.getAttribute('value');
$.ajax({
url : "manageOrganization",
method : "GET",
dataType: "json",
contentType: 'application/json',
data: {organizationId : value },
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
controller
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
here i should get the string to the jsp as a ajax response, but i am getting the error message. Any body can help me.
Regards Sree
For json response you need to add #ResponseBody annotation to your controller method.
You need to use type:"GET" not method:"GET" try it like,
$.ajax({
url : "manageOrganization",
type : "GET", // its type not method
dataType: "json",
.....
Read jQuery.ajax()
Also check that you are returning a json or not.
Your controller is returning String which may be resolved into some other jsp file IF you have configured viewResolver in spring configuration file. Try adding #ResponseBody like this:
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public #ResponseBody
String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}

How do I return a view from a spring controller using an ajax request?

I make an ajax request using jquery, this calls the following spring controller:
#RequestMapping(value = "/dialogController", method = RequestMethod.POST)
public String dialogController(Model model, #RequestBody MyClass myclass) {
myClass.setTitle("SUCCESS");
model.addAttribute("myClass",myClass);
return "dialogContent"; //this resolves to dialogContent.jsp
}
However I receive the following error :
org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' not supported
And if required here is the ajax call I am making using jQuery:
jq.postJSON("/dialogController", myClass, function(data) {
myDialog.html(data);
myDialog.dialog('open');
//dialog settings previously assigned,
//but the success callback function is not reached anyway
});
EDIT
I get same error if I use :
jq.ajax({
type: 'POST',
url: "/dialogController",
data:myClass,
success: function(data) {
previewDialog.html(data);
previewDialog.dialog('open');
});
For the viewers at home ... I found that the problem was due to the method signature defined in controller not matching the ajax call. I removed the Model model parameter from controller method. I also then realized I had to also return a new model and view; here is the working code:
var myJSON = {"title":"help"};
myJSON = JSON.stringify(myJSON);
<c:url var="postAndView" value="/PostJSONMAV" />
...
jQuery.ajax({
type: 'POST',
url: "${postAndView}",
data:myJSON,
contentType: "application/json",
success: function(data) {
previewDialog.html(data);
previewDialog.dialog('open');
}
});
I changed to the ajax call but jQuery.postJSON() will probably work aswell. And shown below is the new controller code, which corrrectly adds a new object to model and returns jsp page, which is opened up in a dialog:
#RequestMapping(value = "/PostJSONMAV", method = RequestMethod.POST)
public ModelAndView postJSON(#RequestBody MyClass myClass) {
ModelAndView mav = new ModelAndView();
myClass.setTitle("SUCCESS");
mav.setViewName("dialogContent");
mav.addObject("myClass", myClass);
return mav;
}

Categories

Resources