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;
}
以不同的方式,我可以根据需要添加额外的标题,但是在生成纯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
带有转义字符而不是纯字符串的字符串,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
根据特定控制器的特定操作的条件生成带有附加标头的纯。