SpringMVC中Controller的@ResponseBody注解分析


需求分析:需要 利用    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);

且不會在頁面上輸出字符串。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM