大家好我想尝试将数据作为参数发送到spring mvc方法,该方法应该使用@RequestParam捕获参数:
@ResourceMapping(value="send")
public void send(ResourceResponse response,@RequestParam("message") String message) throws JsonGenerationException, JsonMappingException, IOException{
System.out.println("send method invocked");
System.out.println("message === >" + message);
.........
和我的角度JS脚本(不工作)如下
var message = "message="+JSON.stringify({
"name" : $scope.message.name ,
"email" : $scope.message.email ,
"tel": $scope.message.tel,
"id_subject":$scope.message.selectedSubject ,
"content" : $scope.message.content
});
console.log("valid");
$http.post('${send}', message)
.success(function(data, status, headers, config) {
})
.error(function(data, status, headers, config) {
});
来自控制器抛出异常的方法(必需字符串参数'消息'不存在) 请帮忙
答案 0 :(得分:2)
Controller.java:
@RequestMapping(value = "/send",
method = {RequestMethod.POST},
consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.OK)
public void place(@RequestBody Message msg) {
//do something with msg
}
Message.java:
public class Message {
//All your fields
private String name;
private String email
//and so on...
/*
* Getters and setters for the fields.
* You can use @Data annotation from Lombok library
* to generate them automatically for you.
*/
public String getName() { return name; }
public String getEmail() { return email; }
}
角度部分:
var message = {name: $scope.message.name, email: $scope.message.email};
$http.post('/send', message)
.success(function() {
console.log("msg sent");
})
.error(function() {
console.log("msg failed");
});
您可能还需要配置Spring以使用Jackson进行JSON转换:
Is it possible to convert from JSON to domain object with @RequestParam