@RequestBody获取Json请求数据

来源:互联网 发布:cf客户端数据异常36 2 编辑:程序博客网 时间:2024/06/06 02:46
使用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)@ResponseBodypublic 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)@ResponseBodypublic 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
0 0
原创粉丝点击