简体   繁体   中英

Return Custom object from Spring Controller

I'm sending an ajax request from a web page which get's mapped to a method in my controller. I return type of this method I have set to a custom MessageForm object, which I create inside the method.

The problem is I'm getting a 500 internal server error when I send the ajaz request, but don't know why.

Do I have to return a specific object from a controller method?

Thanks.

A standard controller method is going to return something with reference to the view associated with it (a ModelAndView or just a String matching the view name, for example).

If you want to return custom objects, you need to specify that the response body is content, rather than a view reference. You can do this with the @ResponseBody annotation.

@RequestMapping(value = "getSomeList.do", method = RequestMethod.GET)
public @ResponseBody List<String> getSomeList() {
    List<String> myList = getMyList();

    return myList;
}

Combined with a library like Jackson , you can serialize this to JSON and make it easily parsable in your view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM