如何在Response Body上添加其他标头

Md *_*ain 21 spring json spring-mvc

只需查看SpringMVC-3.2.x控制器操作方法的代码片段即可.它很容易生成,JSON但无法为特定控制器的此操作/特定操作方法添加addtional自定义标头.对所有JSON @ResponseBody行动方法都不常见.

@RequestMapping(value="ajaxDenied", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> ajaxDenied(ModelMap model) {

    Map<String, Object> message = new HashMap<String, Object>();
    message.put("severity", "error");
    message.put("summary", "Restricted access only");
    message.put("code", 200);

    Map<String, Object> json = new HashMap<String, Object>();
    json.put("success", false);
    json.put("message", message);

    return json;
}
Run Code Online (Sandbox Code Playgroud)

以不同的方式,我可以添加额外的标题作为我的需求,但这是生成纯粹的一些问题JSON.它生成错误JSON并能够解析几个浏览器.

@RequestMapping(value="ajaxSuccess", method = RequestMethod.GET)
public ResponseEntity<String> 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);

    String data = "";
    try {
        ObjectMapper mapper = new ObjectMapper();
        data  = mapper.writeValueAsString(json);
    } catch (Exception e) { //TODO
    }
    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<String>(data, headers, HttpStatus.OK));
}
Run Code Online (Sandbox Code Playgroud)

这个动作方法可以生成JSON具有转义字符而不是纯粹的字符串,JSON因此依赖于浏览器将如何解析它,导致chrome失败.输出看起来像

"{\"message\":{\"summary\":\"Authenticated successfully.\",\"location\":\"/\",\"severity\":\"info\",\"code\":\"200\"},\"success\":true}"
Run Code Online (Sandbox Code Playgroud)

但我们想要的输出

{
  "message":{
    "summary": "Authenticated successfully.",
    "location":"/",
    "severity":"info",
    "code":"200"
  },
  "success":true
}
Run Code Online (Sandbox Code Playgroud)

我想JSON根据特定控制器的特定操作的条件生成带有附加头的纯.

var*_*en_ 28

您可以将标头添加到ResponseEntity构建器.我认为这样更干净.

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);
}
Run Code Online (Sandbox Code Playgroud)


Md *_*ain 17

这是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));
}
Run Code Online (Sandbox Code Playgroud)


Ram*_*rek 6

您还可以使用HttpServletResponse以更简单的方式添加状态和标头:

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

因此,您需要按提供的方式添加以下maven依赖项:

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-servlet-api</artifactId>
    <version>7.0.53</version>
    <scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)