Spring Controller + Ajax return String

I want to return String from Spring MVC Controller to Ajax . It does not work as expected and gives an 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?

+6
source share
3 answers

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

Modify your ajax to add an Accept header for text/plain .

+5
source

I solved it. We can return the correct values ​​using the author of the answers.

  @RequestMapping(value = "/myPage") public void myController(HttpServletRequest request, HttpServletResponse response) throws IOException { String myItem = request.getParameter("item"); ... response.getWriter().println(myItem + "bla bla bla"); } 
+4
source

Make sure you have a dependency on Jackson. Spring MVC can rely on it.

-1
source

All Articles