spring mvc ajax json post,Ajax POST call to Spring MVC

As the only answer says that we need to return json from Controller not ModelAndView. So the question is

what can be done to return ModelAndView ?

How the page will be rendered:-

will it have to be handled in success section of ajax call

Or Spring Controller will return the page as usually it does in Spring MVC

How the post data from ajax can be read in Controller.

Update 1:

As explained, I tried example. here is my code.

@Controller

public class AppController

{

@RequestMapping(value="/greeting",method=RequestMethod.POST)

@ResponseBody

public ModelAndView getGreeting(@RequestBody String json) throws IOException

{

JSONObject inputjsonObject = new JSONObject(json);

String name = inputjsonObject.getString("name");

ModelAndView modelAndView = new ModelAndView();

String result = "Hi "+name;

modelAndView.addObject("testdata", result);

modelAndView.addObject("user", getPrincipal());

modelAndView.setViewName("greetingHtmlPage");

return modelAndView;

}

// other stuff

}

In above controller method i can get data sucessfully. This method is called from a javascript on home.html. Below is javascript function

function callGreeting(){

var nameData={

name : document.getElementById("name").value

}

var dataInJson = JSON.stringify(nameData);

var csrf_token = document.getElementById("token").value;

$.ajax({

type: 'POST',

url: "greeting",

data: dataInJson,

cache:false,

beforeSend: function(xhr) {

xhr.setRequestHeader('X-CSRF-Token', csrf_token);

xhr.setRequestHeader("Accept", "application/json");

xhr.setRequestHeader("Content-Type", "application/json");

},

success: function (response) {

document.open();

document.write(response);

document.close();

},

error: function (data) {

alert("failed response");

}

}); }

I have the page rendered successfully. But the url of application does not changes from AjaxSpringMVC:8080/home to AjaxSpringMVC:8080/greeting even after new page was loaded. This happens by itself in Spring MVC if using without Ajax.