【问题标题】:How to pass object/multiple arguments from Angularjs factory to spring controller如何将对象/多个参数从 Angularjs 工厂传递给 spring 控制器
【发布时间】:2014-06-03 00:45:41
【问题描述】:

我是 Angularjs 的新手,所以请多多包涵, 我有一个要求,我必须将一个对象从 AngularJS 中的 controller.js 传递给工厂,它调用一个休息服务,并且该对象参数被传递给 Spring Controller。我怎样才能做到这一点?我正在尝试的以下方法是给 null @ Spring 控制器。

这是我的 Controller.js:

    if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
            }
            function showPosition(position) {

                $scope.PostLoc = {latitude: null, longitude: null };

                var lat = position.coords.latitude;
                var longi = position.coords.longitude;

                $scope.PostLoc.latitude = lat;
                $scope.PostLoc.longitude = longi;

                $scope.allresultsfinal = PostFactory.alllocresults.query({tag: $scope.PostLoc});

            }

这是我的服务工厂:

  alllocresults: $resource('/ngdemo/web/posts/loc/:tag', {}, {
        query: {method: 'GET', isArray: true, params: {tag: '@tag'} },
        create: {method: 'POST'}
    }),

还有我的 Spring 控制器签名:

   @RequestMapping(value = "/loc/{tag}", method = RequestMethod.GET, produces = "application/json")
public
@ResponseBody
MatchResult resultsByUserLocation(@QueryParam(value = "tag") PostLoc tag) {

请帮我解决我缺少的问题以及如何在我的 spring 控制器中获取该对象?

任何回复将不胜感激

【问题讨论】:

    标签: spring angularjs rest spring-mvc angularjs-directive


    【解决方案1】:

    您在 URL 上传递路径变量,而不是查询参数,因此请在方法签名中声明:

    @RequestMapping(value = "/loc/{tag}", method = RequestMethod.GET, produces = "application/json")
    public
    @ResponseBody
    MatchResult resultsByUserLocation(@PathVariable("tag") PostLoc tag) {
        // ...
    

    这假设(可能是错误的)PostLoc 扩展了java.lang.String。请注意,您不能将对象传递给 URL 路径变量,只能传递字符串。如果您想传入一个对象,则必须在请求正文中执行此操作,或者只需传递一些字符串 ID 并从后端的模型中获取 PostLoc

    【讨论】:

    • 我试过了,它抛出了这个错误:“无法将'java.lang.String'类型的值转换为所需的'ngdemo.model.PostLoc'类型;嵌套异常是java.lang.IllegalStateException : 无法将类型 [java.lang.String] 的值转换为所需类型 [ngdemo.model.PostLoc]:找不到匹配的编辑器或转换策略”
    • 这是否意味着使用 @RequestBody 应该可以工作?因为我使用的是angular js,没有发送任何模型
    • 通过使用@RequestBody,它抛出了Unsupported Media type!
    • 我没有说使用@RequestBodyPostLoc 是什么?它应该来自哪里?它在某个地方持续存在吗?
    猜你喜欢
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2014-03-21
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多