How can I get data from spring controller by ajax? How can I get data from spring controller by ajax? ajax ajax

How can I get data from spring controller by ajax?


You have to add the @ResponseBody annotation for spring ajax calls example

@RequestMapping("/check")     @ResponseBodypublic String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {    boolean a = getSomeResult();    if (a == true) {        model.addAttribute("alreadySaved", true);        return view;    } else {        model.addAttribute("alreadySaved", false);        return view;    }}


use @ResponseBody

Spring will bind the return value to outgoing HTTP response body when you add @ResponseBody annotation.

@ResponseBodypublic String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {    boolean a = getSomeResult();    if (a == true) {        return "already saved";    }     return "error exist";}

Spring will use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type used in request HTTP header.

for more info:

http://websystique.com/springmvc/spring-mvc-requestbody-responsebody-example/


Controller part

You have to add the @ResponseBody annotation for spring ajax calls example

View Part

$.ajax({    type : "GET",    url : "${pageContext.request.contextPath}/check",    data : {        "id" : ${articleCount}    },    success: function(data){        $('#input_field').val(data);    }});