SpringMVC中Controller的@ResponseBody註解分析
阿新 • • 發佈:2019-02-16
需求分析:需要 利用 out 物件返回給財付通是否接收成功 。那麼將需要如下程式碼:
/** * 返回處理結果給財付通伺服器。 * @param msg: Success or fail。 * @throws IOException */ public void sendToCFT(String msg) throws IOException { String strHtml = msg; PrintWriter out = this.getHttpServletResponse().getWriter(); out.println(strHtml); out.flush(); out.close(); }
那麼在Controller中的方法若用此方法註解:
//財付通返回URL @ResponseBody @RequestMapping("/pay/tenpay") public String tenpayReturnUrl(HttpServletRequest request, HttpServletResponse response) throws Exception { unpackCookie(request, response); payReturnUrl.payReturnUrl(request, response); return "pay/success"; }
用此辦法註解將會在訪問的頁面上輸出 字串:strHtml,而不會跳轉頁面至pay/success.jsp頁面
原因是:
@ResponseBody
作用:
該註解用於將Controller的方法返回的物件,通過適當的HttpMessageConverter轉換為指定格式後,寫入到Response物件的body資料區。
使用時機:
返回的資料不是html標籤的頁面,而是其他某種格式的資料時(如json、xml等)使用;
那麼只需刪除註解:@ResponseBody 便可以返回頁面pay/success.jsp。而且達到了與客戶端後臺互動的效果。即:
且不會在頁面上輸出字串。out.println(strHtml);