您的位置:首页 > 产品设计 > UI/UE

@RequestBody获取Json请求数据

2016-07-22 09:02 597 查看
使用springmvc在后端获取前端发送的json数据,使用的是@requestBody注解,前后端代码如下
$("#submitCode").click(function() {
var code = editor.getValue();
$.ajax({
type : "POST",
url: "compileJava",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
Accept: "application/json"
},
data: {code: code},
success : function(data) {
alert(data.msg);
$("#response").html(data.msg);
}
});
});

@RequestMapping(value = "/compileJava", method = RequestMethod.POST)
@ResponseBody
public Object CompileJava(HttpServletRequest request, @RequestBody String code) {
String path = request.getSession().getServletContext().getRealPath("/file/java");
System.out.println(code);
try {
path = compileService.savaJava(code, path);
if (path == null) {
return false;
}
String ans = compileService.compileJava(path);
System.out.println("ans"+ans);
if (ans.length() > 1000) {
ans = ans.substring(0, 1000)+".....";
}
if (ans.trim().length() > 0) {
return new Result(true, ans);
}
else {
return new Result(true, "编译成功");
}
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "编译失败");
}
}

但是收到的code是base64编码之后的,于是将String类型的code改成对象类型。
@RequestMapping(value = "/compileJava", method = RequestMethod.POST)
@ResponseBody
public Object CompileJava(HttpServletRequest request, @RequestBody Src code) {
String path = request.getSession().getServletContext().getRealPath("/file/java");
System.out.println(code.getCode());
try {
path = compileService.savaJava(code.getCode(), path);
if (path == null) {
return false;
}
String ans = compileService.compileJava(path);
System.out.println("ans"+ans);
if (ans.length() > 1000) {
ans = ans.substring(0, 1000)+".....";
}
if (ans.trim().length() > 0) {
return new Result(true, ans);
}
else {
return new Result(true, "编译成功");
}
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "编译失败");
}
}

改完之后无法访问到这个接口了,参数不匹配,于是把前端ajax改成如下
$("#submitCode").click(function() {
var code = editor.getValue();
$.ajax({
type : "POST",
url: "compileJava",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
Accept: "application/json"
},
data: JSON.stringify({code: code}),
success : function(data) {
alert(data.msg);
$("#response").html(data.msg);
}
});
});

时间有限,需要加深了解springmvc的json自动转换机制。 http://blog.csdn.net/kobejayandy/article/details/12690555
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: