json 如何在响应正文上添加额外的标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19970180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I could add additional header on Response Body
提问by Md Shahed Hossain
Just see the code snippet of SpringMVC-3.2.xcontroller action method. Its quite easy to generate JSONbut unable to add addtional custom header only for this action/specific action method for specific controller. not common for all JSON@ResponseBodyaction method .
只需查看SpringMVC-3.2.x控制器操作方法的代码片段即可。它很容易生成,JSON但无法仅为特定控制器的此操作/特定操作方法添加额外的自定义标头。并非所有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;
}
In the different way I could add additional headers as my demand but here is some problem in generating pure JSON. Its generate buggy JSONand able to parse few browser.
以不同的方式,我可以根据需要添加额外的标题,但在生成纯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));
}
this action method could generate JSONString with escape character rather than pure JSONso depend on browser how it will be parse, Its cause failure for chrome. The output just look like
此操作方法可以生成JSON带有转义字符而不是纯字符串的字符串,JSON因此取决于浏览器将如何解析它,这会导致 chrome 失败。输出看起来像
"{\"message\":{\"summary\":\"Authenticated successfully.\",\"location\":\"/\",\"severity\":\"info\",\"code\":\"200\"},\"success\":true}"
but our desired output
但我们想要的输出
{
"message":{
"summary": "Authenticated successfully.",
"location":"/",
"severity":"info",
"code":"200"
},
"success":true
}
I want to generate pure JSONwith additional headers based on conditions for specific action of specific controller.
我想JSON根据特定控制器的特定操作的条件生成带有附加标头的纯。
采纳答案by Md Shahed Hossain
Here is the solution as the suggestion of M. Deinum
这是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));
}
回答by vargen_
You can add headers to the ResponseEntity builder. I think it is cleaner this way.
您可以将标头添加到 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);
}
回答by Ramazan Gevrek
You can also use HttpServletResponsefor adding your status and headers in a more easy way:
您还可以使用HttpServletResponse更简单的方式添加状态和标题:
@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:
因此,您需要添加以下提供的maven 依赖项:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.53</version>
<scope>provided</scope>
</dependency>

