response.getWriter().println和@ResponseBody的比较及同时使用(用于回调函数)

@RequestMapping(value = "/test", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public Object test(@RequestParam Map<String, Object> params, HttpServletRequest request,
HttpServletResponse response) {
logger.info("mobileMethodEntrance请求成功");
// 方法参数
String methodString = request.getParameter("method");
// 跨域
String callbackfun = request.getParameter("callback");

try {
// 反射
Class<DianliMobileApiController> clazz = (Class<DianliMobileApiController>) Class
.forName("com.jysoft.resource.control.DianliMobileApiController");
// 实例化
DianliMobileApiController ins = clazz.newInstance();

// 注入属性
ins.service = SpringUtils.getBean(DianLiMobileApiService.class);

ins.vService = SpringUtils.getBean(VideoService.class);

ins.sservice = SpringUtils.getBean(SupervisionService.class);

// 获取方法
Method method = clazz.getMethod(methodString, HttpServletRequest.class, HttpServletResponse.class);
// 方法调用
Object result = method.invoke(ins, request, response);

Object res = JSON.toJSON(result);

if (!StringUtil.isEmptyString(callbackfun)) {
callbackfun += "(" + res + ")";
response.getWriter().println(callbackfun);
return null;
}

return res;

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

}

备注:

  @RequestMapping("/login")
  @ResponseBody
  public User login(User user){
    return user;
  }
  User字段:userName pwd
  那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'

  效果等同于如下代码:
  @RequestMapping("/login")
  public void login(User user, HttpServletResponse response){
    response.getWriter.write(JSONObject.fromObject(user).toString());
  }

原文地址:https://www.cnblogs.com/keyi/p/11351896.html