2014-02-10 70 views

回答

0

我一直這樣做。我所做的是,不是發回一個「View」字符串或「ModelAndView」對象,而是返回一個ResponseEntity類型的對象。

例如,在你的控制器類,你可以有這樣的方法:

@RequestMapping(value="/cache/clear", method = RequestMethod.GET) 
public ResponseEntity<String> clearAllCaches() { 
    Map<String, Object> results = new HashMap<String, Object>(); 
    long startTimestamp = System.currentTimeMillis(); 
    for (CachingService cachingService : cachingServices) { 
     LOGGER.info("Clearing caches in " + cachingService.getClass().getSimpleName()); 
     cachingService.clearCache(); 
    } 
    long finishTimestamp = System.currentTimeMillis(); 
    long executionTime = finishTimestamp - startTimestamp; 
    LOGGER.warn("Finished clearing caches in " + cachingServices.size() + " services in " + executionTime + " ms."); 
    results.put("executionTime", executionTime); 
    results.put("serviceCount", cachingServices.size()); 
    results.put(ServiceConstants.RETURN_KEY_SUCCESS, Boolean.TRUE); 
    return createResponse(results, HttpStatus.CREATED); 
} 

protected ResponseEntity<String> createResponse(Map <String, Object> results, HttpStatus successCode) { 
    JSONSerializer serializer = new JSONSerializer(); 
    String responseBody = serializer.deepSerialize(results); 
    HttpStatus status = successCode; 
    boolean success = results.containsKey(ServiceConstants.RETURN_KEY_SUCCESS) 
          ? (Boolean)results.get(ServiceConstants.RETURN_KEY_SUCCESS) 
          : false; 
    if (!success) { 
     status = HttpStatus.BAD_REQUEST; 
    } 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.APPLICATION_JSON); 
    headers.setContentLength(responseBody.length()); 
    headers.add("Access-Control-Allow-Origin", "*"); 
    return new ResponseEntity<String>(responseBody, headers, status); 
} 

請注意,我用FlexJSON因爲我使用的Spring Roo。你也可以手動調用Jackson。

0

我解決了我的問題,通過註解@ResponseBody將字符串發送回ajax頁面。

public @ResponseBody 
String test() { 
    List<User> users = userDetailsService.test(); 
    for (User user : users) { 
     System.out.println(user); 
    } 
    return "1"; 
}