Search code examples
springspring-mvcspring-roo

Do I need to set response header in Spring contoller


My controller is like this

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

Will not setting a response header pose any problems. I know how to set the response header from this question - In Spring MVC, how can I set the mime type header when using @ResponseBody In my ajax call I specify

datatype: "json"

Is this sufficient or I need to set the header too. Thanks


Solution

  • Since you're manually generating the JSON response as a string, yes you do need to add the header yourself. You can do this by adding an HttpServletResponse argument to the handler method and calling addHeader(...).

    Alternatively (and better I think) is using Spring to help with JSON serialisation automatically. Try adding Jackson to the classpath and instead of returning a string, return your structure. e.g.:

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