【问题标题】:Pass Json data from angular JS to spring REST API and handling it将 Json 数据从 Angular JS 传递到 spring REST API 并处理它
【发布时间】:2017-04-11 17:04:07
【问题描述】:

我正在学习 AngularJSSpring MVC。我陷入了这样一种情况,即我有一个 angularjs 控制器,我从该控制器对 spring 服务进行REST API 调用。我想知道如何在控制器中接受这些 JSON 值并映射到模型(getter 和 setter)。

在插入数据库之前,我在 spring 端进行了一些验证。我也想知道如何将这些错误消息返回给 angula JS 并在屏幕上填充它们。

这是我的 AngularJS 控制器:

var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
    $scope.addconfig = function() {    
        var dataobj = {
            escfirstname : $scope.escfirstname ,esclastname:$scope.esclastname,escage:$scope.escage 
        }
        $http({
            url: "http://localhost:8080/services/AddConfig", 
            method: "POST",
            data: dataobj,
            headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
            }
        });
    }
}); 

这是我的 Spring 服务:

@Controller
public class TestController {
    @RequestMapping(value = "/AddConfig",   method = RequestMethod.POST)
    public @ResponseBody String PostService(@RequestBody Config person) {
        System.out.println("came insidee");
        return null;
    }
}

我可以打印系统输出。现在我想知道如何进行。

【问题讨论】:

  • 可能找不到请求的网址尝试使用localhost:8080/AddConfig编辑
  • 嘿,我可以连接我的服务。我需要知道从 spring 向 Angular 返回错误消息并显示它们的正确方法

标签: angularjs json spring spring-mvc


【解决方案1】:

enter link description here

像这样。

var myapp = angular.module("app");

myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
        $scope.addconfig = function() {    
   var dataObject = {
      escfirstname : $scope.escfirstname, 
      esclastname : $scope.esclastname, 
      escage : $scope.escage
   };

   $http({
      method: 'POST', 
      url: 'http://localhost/jsonURL',
      data: dataObject,
      headers: {'Content-Type': 'application/json; charset=utf-8'} 

   }).success(function(data, status, headers, config) {
      if( data ) {

      }
      else {

      }
   }).error(function(data, status, headers, config) {
      console.log(status);
   });
}
}); 

@Controller
public class TestController {

    @RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
    public @ResponseBody String PostService(@RequestBody Config person) {

        // System.out.println("person" + person.);
        return null;
    }
}

【讨论】:

  • 非常感谢,这正是我想要的 :)
  • 是的。好的,我想看看你的帖子。
  • 如果我是你,我会给我打分:)
  • 我还没有 15 声望来做到这一点! :)
  • 调用服务时收到错误的请求错误
猜你喜欢
  • 2017-04-08
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 2020-11-09
相关资源
最近更新 更多