【问题标题】:Do I need to set response header in Spring contoller我需要在 Spring 控制器中设置响应头吗
【发布时间】:2012-04-07 17:51:17
【问题描述】:

我的控制器是这样的

@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"

这是否足够或者我也需要设置标题。谢谢

【问题讨论】:

    标签: spring spring-mvc spring-roo


    【解决方案1】:

    由于您手动将 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 2013-09-03
      • 1970-01-01
      • 2011-05-21
      • 2020-08-01
      • 1970-01-01
      相关资源
      最近更新 更多