@ResponseBody註解下,後臺幾種傳遞參數的方式

1、@ResponseBody註解的作用是將controller的方法返回的對象通過適當的轉換器轉換爲指定的格式之後,寫入到response對象的body區,通常用來返回JSON數據或者是XML數據,需要注意的呢,在使用此註解之後不會再走試圖處理器,而是直接將數據寫入到輸入流中,他的效果等同於通過response對象輸出指定格式的數據。

2、response.getWriter.write():

@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());
}

3、Map放置對象或者參數:

@ResponseBody  
@RequestMapping(value="findOrder",produces = "application/json;charset=UTF-8" )  
public Map<String, Object> findOrder(HttpServletRequest request,int rows,int page){  
    //以json格式的形式返回數據到前臺easyui控件  
    Map<String,Object> result = new HashMap<String, Object>();  
    result.put("total", count);  
    result.put("rows", list);  
    return result;  
}  

4、JSONObject放置對象或者參數:

@ResponseBody  
@RequestMapping(value="findOrder",produces = "application/json;charset=UTF-8" )  
public Map<String, Object> findOrder(HttpServletRequest request,int rows,int page){  
     JSONObject jsonObj = new JSONObject();
     jsonObj.put("username", "張三");
     jsonObj.put("password", "");
     return jsonObj;  
}  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章