0

I am working with a spring MVC controller which will return a boolean value as response to the ajax request. But when spring mvc is trying to return a boolean value it is giving me the server responded with a status of 406 (Not Acceptable) error Please Help. Thanks in advance

This is my controller

@Controller
public class MainController {
    @RequestMapping(value="/check.html",method=RequestMethod.POST)
    public @ResponseBody Boolean checkValue(){
        return true;
    }
}

This is my Ajax method

<script type="text/javascript">
    function doAjax() {
        $.ajax({
            type : "post",
            url : 'check.html',
            success : function(response) {
                if(response===true)
                {
                    window.alert("true");
                }
                else
                {
                    window.alert("false");
                }
            },
            error : function(e){
                window.alert("error");
            }
        });
    }
</script>

3 Answers 3

1

I was experiencing same problem when I was returning a string to the AJAX request. But I solved it using HttpServletResponse object. You can also do it like this way.

@RequestMapping(value="/check.html",method=RequestMethod.POST)
public @ResponseBody void checkValue(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){

    /*Your Logic*/
    httpServletResponse.getWriter().println(true);
    httpServletResponse.flushBuffer();

}

Now you can get a boolean response and you can use response in your javascript code as a boolean variable.

Sign up to request clarification or add additional context in comments.

Comments

0

I think some primitive values may not be valid JSON. I would normally return a map looking like {"status": true} in such cases.

Comments

0

Try adding the produces attribute to your @RequestMapping so

@RequestMapping(value="/check.html",method=RequestMethod.POST, produces="application/json" )

To understand your problem read about the content negotiation in spring.

The extension of your request check.html is considered when the frameworks reasons about the return type, and it gives a hint that the response should be html. The annotation @ResponseBody tries to add a content to response's body.

When you return a primitive true the framework attempts to find a converter that will convert the true value to HTML. It fails, and you get your error message.

With the produces set to application/json, it will use the underlying converter (jackson if you didn't change the defaults), and it will convert without issues

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.