How do I could add additional header on Response Body

后端 未结 3 727
离开以前
离开以前 2021-02-02 11:08

Just see the code snippet of SpringMVC-3.2.x controller action method. Its quite easy to generate JSON but unable to add addtional custom header only f

相关标签:
3条回答
  • 2021-02-02 11:38

    Here is the solution as the suggestion of M. Deinum

    @RequestMapping(value="ajaxSuccess", method = RequestMethod.GET)
    public ResponseEntity<Map<String, Object>> ajaxSuccess(){
        Map<String, Object> message = new HashMap<String, Object>();
    
        message.put("severity", "info");
        message.put("location", "/");
        message.put("summary", "Authenticated successfully.");
        message.put("code", 200);
    
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("success", true);
        json.put("message", message);
    
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=UTF-8");
        headers.add("X-Fsl-Location", "/");
        headers.add("X-Fsl-Response-Code", "302");
        return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK));
    }
    
    0 讨论(0)
  • 2021-02-02 11:40

    You can also use HttpServletResponse for adding your status and headers in a more easy way:

    @RequestMapping(value="ajaxSuccess", method = RequestMethod.GET)
    @ResponseBody
    public String ajaxSuccess(HttpServletResponse response) {
      response.addHeader("header-name", "value");
      response.setStatus(200);
      return "Body";
    }
    

    Therefore you need to add following maven dependency as provided:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-servlet-api</artifactId>
        <version>7.0.53</version>
        <scope>provided</scope>
    </dependency>
    
    0 讨论(0)
  • 2021-02-02 11:49

    You can add headers to the ResponseEntity builder. I think it is cleaner this way.

    import org.springframework.http.HttpHeaders;
    import org.springframework.http.ResponseEntity;
    
    // ...
    
    @GetMapping("/my/endpoint")
    public ResponseEntity myEndpointMethod() {
    
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
    
        return ResponseEntity.ok()
                .headers(headers)
                .body(data);
    }
    
    0 讨论(0)
提交回复
热议问题