Spring Controller + Ajax return String

12,698

Solution 1

When you return a String from a handler method annotated with @ResponseBody, Spring will use a StringHttpMessageConverter which sets the return content-type to text/plain. However, your request does not have an Accept header for that content-type so the Server (your Spring app) deems it unacceptable to return text/plain.

Change your ajax to add the Accept header for text/plain.

Solution 2

I have solved it. We can return correct values with response writer.

    @RequestMapping(value = "/myPage")
    public void myController(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String myItem = request.getParameter("item");   

    ...

    response.getWriter().println(myItem + "bla bla bla");
    }
Share:
12,698
AkiraYamaokaNC
Author by

AkiraYamaokaNC

Updated on June 06, 2022

Comments

  • AkiraYamaokaNC
    AkiraYamaokaNC about 2 years

    I want to return String from Spring MVC Controller to Ajax. It is not working as expected and gives error.

    My Ajax codes for this:

    function ajaxRequest(item) {
    
        $.ajax({
            type: "POST",
            url: "/myPage",
            data: {
               item: item
            },
            success: function (html) {
    
                alert(html);
            },
            error: function(e) {
                console.log("Error:" + e);
            }
        });
    
    }
    

    My Controller:

    @RequestMapping(value = "/myPage", method= RequestMethod.POST, produces="text/plain")
    public @ResponseBody String myController(HttpServletRequest request) {
    String myItem = request.getParameter("item");   
    
    ...
    
    return myItem + "bla bla bla";
    }
    

    Chrome console result:

    POST http://localhost:8080/myPage 406 (Not Acceptable) jquery.js
    Error:[object XMLHttpRequest] 
    

    What am i missing here?

  • Sotirios Delimanolis
    Sotirios Delimanolis almost 10 years
    Jackson is not involved here.