Hi am using spring mvc + ajax. I made a ajax call by passing a userid. And everything goes fine successfully returned to ajax but when i alert the response its simple showing the html page code. Please help me to sort out this prob.
I think i didnt coded my ajax well.Help me to in correct way
Controller code:
public #ResponseBody ModelAndView abc(HttpServletRequest httpServletRequest,
HttpSession session, ModelMap map){
ModelAndView modelAndView = new ModelAndView("abcd.page",
"commandName", object);
return modelAndView;
Ajax code :
$(".userDetails").click(function() {
alert("clicked");
var userId=$(this).parent().parent(). parent().find(".userId").
text().trim();
alert("userId :"+userId);
$.ajax({
url : 'ABC.htm',
type : 'GET',
data: {userId:userId},
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success : function(response) {
alert("success");
alert(response);
},
error : function(res) {
alert("error");
},
});
return false;
});
The output for the alert(response); is
EDIT: Can any one please tell why ajax giving html content on success... After many changes i made getting the same alert.
Edited Again : I think i dont have any problem in controller. Please suggest me solution to code my ajax correctly. It seems error here. How to get a ModelAndView object in ajax
You don't get a ModelAndView object in AJAX. Spring uses HandlerMethodReturnValueHandler instances to handle your handler method's return value. For ModelAndView, it uses ModelAndViewResolverMethodReturnValueHandler. For #ResponseBody, it uses RequestResponseBodyMethodProcessor. These are checked in a specific order and the one for ModelAndView has higher priority. Therefore, when you return a ModelAndView, Spring will add the model attributes to the full Model and then resolve your view name to, probably, a jsp and write the response from that jsp, giving you some HTML. Since AJAX just sees the response from the request, it will see HTML.
If you want to return JSON, don't return a ModelAndView, return the model object directly or write JSON directly to the response yourself.
Related
I have a JSP page that makes an ajax post to a Java spring controller. However, whenever I make the post, I am getting a 415 Unsupported Media Type error. Since I'm fairly new to Spring MVC, I'm not sure if the error is due to my response type or request type. My ajax looks like:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "POST",
url: "validateRedirect",
context:document.body,
contentType:"application/json",
data:JSON.stringify(validateObject),
dataType:"json"
});
With my request mapping looking like:
#RequestMapping(value = "/validateRedirect", method = {RequestMethod.POST}, headers="Content-Type=application/json")
public ResponseEntity<String> callToValidate(HttpServletRequest servletRequest, HttpServletResponse servletResponse, #RequestBody ValidateObj validateObject)
Even when I try to make a post from Postman, I get the same error, so I'm thinking it's something to do with my response
Try modifying your controller to
#PostMapping(value = "/validateRedirect")
public ResponseEntity<ValidateObj> callToValidate(#RequestBody ValidateObj validateObject)
try it out:
#RestController
public TestController{
#PostMapping("/validateRedirect")
public ResponseEntity<ValidateObj> callToValidate(#RequestBody ValidateObj validateObject){
//...your logic
return new ResponseEntity<ValidateObj>();
}
}
If you are using default settings of spring, it should application/json as default accept and content type. So you don't have to specify in annotation.
Simply, I'm trying to parse a List of composite objects passed from Spring controller via ModelAndView object as the following
Spring part
ModelAndView view = new ModelAndView("my view");
List<ActionHistory> histories = myService.getListData();
view.addObject("histories", histories);
return view;
In Jquery i tried couple of alternatives, first used the below line to construct JSON from List:
var list = JSON.stringify('${histories}');
console.log(histories);
the console is returning
"[com.companyname.projectname.domains.ActionHistory#48126327]"
TypeError: invalid 'in' operand a
I also tried from jquery-json by including "jquery.json.min.js" as a suggestion from this topic discussed but getting the same error above Serializing to JSON in jQuery
var histories = $.toJSON('${histories}');
console.log(histories);
Check you contentType in ajax function it should be.
contentType: "application/json"
Also your Spring controller which is handling this mvc call should configure be configired with
produces=MediaType.APPLICATION_JSON_VALUE
e.g. something like
#RequestMapping(value ="/getList", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
I am new at spring MVC .I am trying to do ajax request on spring MVC. This seem when ajax call act controller method doesnt response.But I didnt understand why it is.
But I am getting this error on browser console:
Failed to load resource: the server responded with a status of http://localhost:8080/spapp/ajaxtest.html 404 (Not Found)
Here My method in controller class:
#RequestMapping(value = "/ajaxtest", method = RequestMethod.POST)
public #ResponseBody String ajaxtest() {
String result = "This is Ajax text from ajaxTest Method";
return result;
}
Here My Ajax call in index.jsp:
$(function(){
$(document).on("click","button#save",function(){
$.ajax({
type:"POST",
url:"ajaxtest.html",
data:{test:"test"},
success:function(response){
$("div#response").html(response);
}
});
});
});
What can I do fix this error?
Thanks
Try with url:"ajaxtest" you don't have to put .html at the end because you have declared your endpoint value = "/ajaxtest".
I found the solution.I removed type="POST" in ajax call.after it runs.
Hey guys, I have a list to be displayed on a view JSP page from the controller side. What do I return from the modelandview function if I want the list to be displayed in the same view page I am calling it from?
Here is the jQuery which i use to call the controller
$("#customerList").on("keydown",function(){
$.ajax({
url: '/omp/customer',
type: 'GET'
});
});
});
Here is the controller code
#RequestMapping(method= RequestMethod.GET)
public ModelAndView getlist(Model mod)
{
System.out.println("I am here");
CustomerDetails details = new CustomerDetails();
details.setAl();
mod.addAttribute("lists",details.getAl());
return new ModelAndView("dashboard/home");
}
It looks like you want to make an Ajax call to the server and retrieve a list.
Ajax calls are asynchronous and don't require to load a new page.
My advise is that the controller should return the list in JSON format and some
javascript should parse and display it.
Have a look at #ResponseBody annotation in the Spring MVC documentation.
I'm familiar with how to return json from my #Controller methods using the #ResponseBody annotation.
Now I'm trying to read some json arguments into my controller, but haven't had luck so far.
Here's my controller's signature:
#RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(#RequestParam("json") #RequestBody SearchRequest json) {
But when I try to invoke this method, spring complains that:
Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'
Removing the #RequestBody annotation doesn't seem to make a difference.
Manually parsing the json works, so Jackson must be in the classpath:
// This works
#RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(#RequestParam("json") String json) {
SearchRequest request;
try {
request = objectMapper.readValue(json, SearchRequest.class);
} catch (IOException e) {
throw new IllegalArgumentException("Couldn't parse json into a search request", e);
}
Any ideas? Am I trying to do something that's not supported?
Your parameter should either be a #RequestParam, or a #RequestBody, not both.
#RequestBody is for use with POST and PUT requests, where the body of the request is what you want to parse. #RequestParam is for named parameters, either on the URL or as a multipart form submission.
So you need to decide which one you need. Do you really want to have your JSON as a request parameter? This isn't normally how AJAX works, it's normally sent as the request body.
Try removing the #RequestParam and see if that works. If not, and you really are posting the JSON as a request parameter, then Spring won't help you process that without additional plumbing (see Customizing WebDataBinder initialization).
if you are using jquery on the client side, this worked for me:
Java:
#RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(#RequestBody SearchRequest json) {
Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):
$.ajax({
type: "post",
url: "sync", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(jsonobject), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(){
alert('failure');
}
});