我开发了一个RESTful Web服务,它有一个POST方法。
我需要返回json
回复。我可以将post方法返回类型为void并在json
正文中设置httpresponse
字符串吗?
或
我是否需要通过将方法返回类型更改为String来返回JSON
字符串?推荐哪一个?请指导我......
谢谢!
答案 0 :(得分:0)
是的,您可以将doPost的返回类型更改为void:
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String value = value; //JSON value you want to return
StringBuilder out = new StringBuilder();
out.append("{\"key\": \"" + value+ "\"}");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(out.toString());
}