我在使用Ajax发送表单时遇到问题。
这是表格:
<form method="POST" id="add-card-form" action="${pageContext.request.contextPath}/card/add" class="form-horizontal">
<select name="type" class="form-control">
<c:forEach items="${cardTypes}" var="cardType">
<option value="${cardType.id}">${cardType.name}</option>
</c:forEach>
</select>
<select name="category" class="form-control">
<c:forEach items="${cardCategories}" var="cardCategory">
<option value="${cardCategory.id}">${cardCategory.name}</option>
</c:forEach>
</select>
<textarea type="text" name="description" class="form-control" rows="6"></textarea>
<input type="submit" id="add-card-submit" value="Add card" class="btn btn-primary"/>
这是Ajax函数:
$(document).on('submit', '#add-card-form', function(e) {
var frm = $('#add-card-form');
e.preventDefault();
var Form = this;
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
//temporary solution
data["type"] = parseInt(data["type"]);
data["category"] = parseInt(data["category"]);
console.log(data);
if(frm.valid()) {
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: frm.attr('method'),
url: frm.attr('action'),
data: JSON.stringify(data),
success: reloadBoard,
error: function (callback) {
console.log(callback);
}
});
refreshForm(frm);
}
});
这是一个控制器动作:
@RequestMapping(value="/add", method = RequestMethod.POST)
public @ResponseBody Card addCard(@RequestBody Integer type,
@RequestBody Integer category,
@RequestBody String description) {
Card card = new Card();
card.setType(cardTypeService.findById(type));
card.setCategory(cardCategoryService.findById(category));
card.setDescription(description);
card.setOwner(1);
cardService.saveCard(card);
System.out.println("Card with id " + card.getId() + " added!");
return card;
}
可变数据值:
Object {type: 1, category: 1, description: "New Card"}
当我尝试发送此表单时,我总是收到错误400:http://localhost:8080/card/add 400 (Bad Request)
你能告诉我这段代码有什么问题吗?我已经使用Spring MVC + Ajax发布了一些关于发送数据的文章,但没有人帮忙。
修改
我将@RequestBody改为三个@RequestParams:
@RequestMapping(value="/add", method = RequestMethod.POST)
public @ResponseBody Card addCard(@RequestParam("type") Integer type,
@RequestParam("description") String description,
@RequestParam("category") Integer category) {
我仍然得到400错误。这是原始HTTP请求:
POST /card/add HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 48
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
Content-Type: application/json; charset=UTF-8
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Referer: http://localhost:8080/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: JSESSIONID=ABAD895C419A9175EAB4D0833C543724
数据对象:
category: 1
description: "New Card"
type: 1
答案 0 :(得分:4)
Dmitry Zolotukhin说的唯一合理的事情就是只有一个@RequestBody
,因为你只能使用一次请求,之后它会被提交,所有后续的读取尝试都将失败。
您应该做的是将Card
类作为方法参数注释为@RequestBody
,所以
@RequestMapping(value="/add", method = RequestMethod.POST)
public @ResponseBody Card addCard(@RequestBody Card card) {
card.setOwner(1);
cardService.saveCard(card);
System.out.println("Card with id " + card.getId() + " added!");
return card;
}
spring mvc框架将处理Card
对象的实例化,并通过将JSON
body中的键与属性进行匹配来将请求值绑定到属性。另请注意,要使其正常工作,您发送的数据必须是有效的json,因此请确保遵守该数据。
您可以考虑创建一个简单的数据传输对象,例如CardDTO
类似
public class CardDTO {
private Integer category;
private Integer type;
private String descrption;
public Integer getCategory() {
return category;
}
public void setCategory(Integer category) {
this.category = category;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getDescrption() {
return descrption;
}
public void setDescrption(String descrption) {
this.descrption = descrption;
}
}
而不是绑定它
@RequestMapping(value="/add", method = RequestMethod.POST)
public @ResponseBody Card addCard(@RequestBody CardDTO cardDTO) {
答案 1 :(得分:0)
@RequestBody
表示HTTP请求正文的内容将映射到该属性。由于您只能拥有一个请求体,因此几乎肯定会失败。
您最有可能需要指定请求参数:@RequestParam("type") String type
如果这没有帮助,您能否从Web服务器的日志/控制台提供原始HTTP请求数据和Spring MVC错误堆栈跟踪?