使用 Spring 传递 JSON 相当简单。考虑以下 jQuery 函数:
function processUrlData(data, callback) {
$.ajax({
type: "GET",
url: "getCannedMessageAsJson.html",
data: data,
dataType: "json",
success: function(responseData, textStatus) {
processResponse(responseData, callback);
},
error : function(responseData) {
consoleDebug(" in ajax, error: " + responseData.responseText);
}
});
}
现在使用以下 String @Controller 方法...
@RequestMapping(value = "/getCannedMessageAsJson.html", method = RequestMethod.POST)
public ResponseEntity<String> getCannedMessageAsJson(String network, String status, Model model) {
int messageId = service.getIpoeCannedMessageId(network, status);
String message = service.getIpoeCannedMessage(network, status);
message = message.replaceAll("\"", """);
message = message.replaceAll("\n", "");
String json = "{\"messageId\": \"" + messageId
+ "\", \"message\": \"" + message + "\"}";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
在我的情况下,请求非常简单,我只是在控制器方法中硬连线 json 格式,但您可以轻松地使用像 Jackson 这样的库来生成 json 字符串。
也正如其他人所说,验证 @RequestMapping 中的“值”是一个唯一的、合法的文件名。使用我上面展示的 json 方法,您不必拥有相应的 jsp 页面(实际上它不会使用)。