2011-05-13 116 views
0

我想從控制器發送JSON對象到我的視圖,但無法發送它。 請幫我一把!從控制器傳遞JSON對象到視圖(jsp)

我使用以下代碼

public class SystemController extends AbstractController{ 

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     ModelAndView mav = new ModelAndView("SystemInfo", "System", "S"); 

     response.setContentType("application/json;charset=UTF-8"); 
     response.setHeader("Cache-Control", "no-cache"); 
     JSONObject jsonResult = new JSONObject(); 

     jsonResult.put("JVMVendor", System.getProperty("java.vendor")); 
     jsonResult.put("JVMVersion", System.getProperty("java.version")); 
     jsonResult.put("JVMVendorURL", System.getProperty("java.vendor.url")); 
     jsonResult.put("OSName", System.getProperty("os.name")); 
     jsonResult.put("OSVersion", System.getProperty("os.version")); 
     jsonResult.put("OSArchitectire", System.getProperty("os.arch")); 

     response.getWriter().write(jsonResult.toString()); 
    // response.getWriter().close(); 

     return mav;    // return modelandview object 
    } 
} 

並且在觀看側我使用

<script type="text/javascript"> 

Ext.onReady(function(response) { 
    //Ext.MessageBox.alert('Hello', 'The DOM is ready!'); 
    var showExistingScreen = function() { 
     Ext.Ajax.request({ 
      url      : 'system.htm', 
      method     : 'POST', 
      scope     : this, 
      success: function (response) { 
       alert('1'); 
       var existingValues = Ext.util.JSON.decode(response.responseText); 
       alert('2'); 
       } 
     }); 
    }; 

    return showExistingScreen(); 
}); 
+0

請幫助我! – user752233 2011-05-13 11:54:55

回答

1

爲了發送JSON回客戶端我成功地使用以下解決方案:

1 )客戶端(瀏覽器)向我的SpringMVC控制器發送一個包含JSON格式值(但也可以是GET)的AJAX POST請求。

$.postJSON("/login", login, function(data) 
{ 
    checkResult(data); 
}); 

2)控制器用SpringMVC方法簽名:

@RequestMapping(value = "/login", method = RequestMethod.POST) 
public @ResponseBody Map<String, String> 
login(@RequestBody LoginData loginData, 
HttpServletRequest request, HttpServletResponse response) 

@ResponseBody是關鍵,它」 ......表示該返回類型應當直接寫入HTTP響應主體(而不是放置在模型中,或者解釋爲視圖名稱)。「 [Spring Reference Doc] LoginData是一個簡單的POJO容器,用於來自客戶端請求的JSON值,如果您將傑克遜jar文件(我使用jackson-all-1.7.5.jar)放入類路徑中,它會自動填充。 由於控制器方法的結果,我創建了一個hashMap <字符串,字符串>。 (例如,鍵'錯誤'或'查看'和適當的值)。然後這個地圖被自動序列化成客戶端解釋的JSON(同樣是普通的html頁面,包括Javascript)

function checkResult(result) 
{ 
    if (result.error) 
    { 
     // do error handling 
    } 
    else 
    { 
     // use result.view 
    } 
} 
相關問題