【问题标题】:AngularJS send data to spring mvc methodAngularJS向spring mvc方法发送数据
【发布时间】:2015-05-21 16:41:40
【问题描述】:

大家好,我正在尝试将数据作为参数发送到 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);
    .........

我的 Angular 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) {

              });

控制器抛出异常的方法(必需的字符串参数“消息”不存在) 请帮忙

【问题讨论】:

  • 你应该尝试@RequestBody 和 POST http 方法,这是处理 json 数据的更好方法
  • 它是 JSR 286 而不是简单的 spring web mvc

标签: angularjs spring spring-mvc


【解决方案1】:

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

【讨论】:

  • 首先感谢 Arseny 先生的回复。您的代码适用于 Spring Web MVC 应用程序我使用 JSR 286(portlet api 2)和 Spring Web MVC Portlet,所以我不能使用 @RequestMapping
猜你喜欢
  • 2016-09-21
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 2011-07-09
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
相关资源
最近更新 更多