我目前正在开发spring mvc
申请,我需要发布JSON array
。
当我访问request.getParameter("paramValue")
以获取参数attibute,但它返回null
值时,
这是我的前端代码:
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
"test":"test value"
})
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
这是我的服务器端代码:
@RequestMapping(value = "/Products", method = RequestMethod.POST)
public void saveProducts(HttpServletRequest req, HttpServletResponse res) throws Exception {
System.out.println(req.getContentType());
System.out.println(req.getContentLength());
System.out.println(req.getContextPath());
System.out.println(req.getParameterValues("test"));
System.out.println(req.getMethod());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = req.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);
System.out.println(req.getParameter("test"));
}
输出结果为:
application/json
22
null
POST
{"test" : "Test DAta"}
null
我无法弄清楚发生了什么,请帮助我。
答案 0 :(得分:0)
在你的ajax函数中删除这一行
contentType: 'application/json',
并替换此行
data: JSON.stringify({
"test":"test value"
})
带
data: {
"test":"test value"
}
也可以使用
req.getParameter("test")
代替
req.getParameterValues("test")
答案 1 :(得分:0)
你可以使用这个:
var data ={id: 1, name :'test'}
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: data
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
并在服务器端 创造一个pojo:
public class Product{
private long id;
private String name;
// getters and setters
添加库杰克逊。
在您的控制器中添加此方法:
@RequestMapping(value = "/Products", method = RequestMethod.POST)
public RepsoneEntity<? >saveProducts(@requestBody Product pr){
LOG.debug(pr.toString());
return new reRepsoneEntity<Product>(pr,HttpStatus.ACCEPTED);
}
答案 2 :(得分:0)
我最后修改了几个注释并更改了服务器端方法的返回类型,
@RequestMapping(value = "/Products", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<?> saveProducts(@RequestParam(value = "data") String brand) {
return ResponseEntity.ok(brand);
}</code>
front end
$.ajax(url, {
async: true,
type: "POST",
data: {"data" : JSON.stringify({"Brand" : "Test Brand"})}
}).done(function (response) {
console.log(response);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
public ResponseEntity<?> saveProducts(@RequestParam(value = "data") String brand) {
return ResponseEntity.ok(brand);
}</code>
我使用org.json来访问被解析为文本的json对象,gson来处理POJO
现在可行了:)