如何在响应正文上添加其他标题
只需查看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;
}
以不同的方式,我可以根据需要添加其他标头,但这在生成pure时存在一些问题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));
}
此操作方法可能会生成JSON
带有转义字符而不是纯字符的String,JSON
因此取决于浏览器如何解析,这会导致chrome失败。输出看起来像
"{\"message\":{\"summary\":\"Authenticated successfully.\",\"location\":\"/\",\"severity\":\"info\",\"code\":\"200\"},\"success\":true}"
但是我们想要的输出
{ "message":{
"summary": "Authenticated successfully.",
"location":"/",
"severity":"info",
"code":"200"
},
"success":true
}
我想JSON
根据特定控制器的特定操作的条件生成带有其他标头的纯文本。
回答:
这是 *
@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));
}
以上是 如何在响应正文上添加其他标题 的全部内容, 来源链接: utcz.com/qa/418666.html