Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Controller method returning void produce JSON?

Normally to return JSON from my Controllers methods, I add a @ResponseBody annotation and I let Jackson to map my returned object as JSON. No problem here.

However in this question, the OP says "my other methods that use @RequestMapping return void, and I can still get JSON from them through ajax".

I was wondering how's that possible? I've no reason to doubt, that he's indeed doing that, so I would like to know how to do that, for the sake of curiosity and enhancing my Spring understanding.

like image 239
stivlo Avatar asked Mar 16 '26 12:03

stivlo


1 Answers

You can write directly to the HttpServletResponse:

@ResponseBody
public void doSomething(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    String json = "{\"Hello\": \"World\"}";
    PrintWriter out = response.getWriter();
    out.write(json);
}
like image 162
Danalog Avatar answered Mar 19 '26 01:03

Danalog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!