这是我原先的代码
js代码
$.get('http://localhost:8080/raxly-original/page?id=1', function(res) {
console.log(res);
})
Servlet 代码
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
String id = request.getParameter("id");
if (id != null) {
Page resultPage = pageService.getById(Integer.valueOf(id));
PrintWriter writer = response.getWriter();
writer.print(resultPage); // print一个普通实体, 前端接收后是一串字符串
writer.flush();
writer.close();
}
}
然后自己改良了一下, 就是在前端手动把String转成json, 代码如下
$.get('http://localhost:8080/raxly-original/page?id=1', function(res) {
console.log(JSON.parse(res));
})
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
String id = request.getParameter("id");
String responseContent = null;
if (id != null) {
Page resultPage = pageService.getById(Integer.valueOf(id));
// { "pageId":"%s", "pageName":"%s" }
responseContent = String.format("{ \"pageId\":\"%s\", \"pageName\":\"%s\" }", resultPage.getPageId(), resultPage.getPageName());
PrintWriter writer = response.getWriter();
writer.print(responseContent);
writer.flush();
writer.close();
}
}
有没有更优的方案?
可以实现后端直接传对象, 前端自动解析成json的?
用jackson, Gson, fastjson等, 把对象转成json字符串, 写到输出 流, 再加个header
content-type: application/json
就行.别听那些说什么用spring的. 用spring当然 好. 但你要求用servlet, 就是答非所问.