2012-03-23 32 views
0

我的控制器是這樣我是否需要設置響應頭春位指示

@RequestMapping(value ="/getTaggedProducts", method = RequestMethod.GET) 
@ResponseBody 
public String getProductsTagged(@RequestParam("questionnaireId")Long questionnaireId){ 
    Map<String, Object> response = new HashMap<String, Object>(); 
    try{ 
     Questionnaire questionnaireProduct = Questionnaire.findQuestionnaire(questionnaireId); 
     Organisation userOrg = getUserAffiliation(); 

     if (questionnaireProduct == null) throw new QuestionnaireBuilderException("Questionnaire '" + questionnaireId + "'does not exist"); 
     if (!questionnaireProduct.isEditable()) throw new QuestionnaireBuilderException("You cannot edit a questionnaire which has been assigned"); 

     Set<Product> productCategories = questionnaireProduct.getProducts(); 
     List<Long> productIds = new ArrayList<Long>(); 
     for(Product p: productCategories){ 
      productIds.add(p.getId()); 
     } 

     LOG.debug("Product Categories successfully added to questionnaire"); 
     response.put("message", "success"); 
     response.put("products", productIds); 
    } catch (QuestionnaireBuilderException e) { 
     LOG.debug(e.getMessage(), e); 
     response.put("message", e.getMessage()); 
    } catch (Exception e) { 
     LOG.error("Unhandled Exception: " + e.getMessage(), e); 
     response.put("message", "Unhandled Exception"); 
    } 
    return new JSONSerializer().exclude("*.class").deepSerialize(response); 
} 

不會設置響應頭引起任何問題。我知道如何從這個問題設置的響應頭 - In Spring MVC, how can I set the mime type header when using @ResponseBody 在我的Ajax調用我指定

datatype: "json" 

這是足夠的,或者我需要設置的頭了。謝謝

回答

0

由於您手動生成JSON響應作爲字符串,是的,你需要自己添加頭。 您可以通過向處理程序方法添加HttpServletResponse參數並調用addHeader(...)來完成此操作。

或者(我認爲更好)是使用Spring自動幫助JSON序列化。嘗試將Jackson添加到類路徑中,而不是返回一個字符串,返回您的結構。例如:

@RequestMapping(value="/getTaggedProducts",method=RequestMethod.GET) 
@ResponseBody 
public Map<String,Object> getProductsTagged(@RequestParam("questionnaireId") Long questionnaireId) { 
    final Map<String,Object> json = ...; 
    return json; 
} 
相關問題