【问题标题】:Spring Controller not returning JSON data to angular http GET callSpring Controller 未将 JSON 数据返回到 Angular http GET 调用
【发布时间】:2019-05-15 12:00:05
【问题描述】:

我有一个如下所示的弹簧控制器:

@RestController
public class RaceResultController {

    @Autowired
    RaceResultImpl raceResultImpl;

    @GetMapping("/race")
    public ModelAndView hello(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

        List<RaceTopResult> raceTopResultList = raceResultImpl.getResults();
        ObjectMapper o = new ObjectMapper();
        model.addAttribute("races", raceTopResultList);
        return new ModelAndView("race");


    }
}

然后我的视图race.html中有一些嵌入的角度代码:

      <head>
        <title>F1 RESULTS 2018</title>
         <script 


      src=
    "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> .    
     </script>
      <script 
       src=
    "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
     </head>
     <body>
     <header>
        <h1>F1 RESULTS 2018</h1>
     </header>
      <div ng-app="raceApp" ng-controller="raceCtrl">
        <table id="my_table" border = "1">
            <tr ng-repeat="race in races">
                <td>{{ race.driver }}</td>
                <td>{{ race.team }}</td>
            </tr>
        </table>
     </div>

    </body>

    <script>
        var app = angular.module('raceApp', []);
        app.controller('raceCtrl', function($scope, $http) {
            alert("mini");
            $http({
                url: "/race",
                method: "GET",
                dataType: 'json'
                 }).then(function successCallback(response) {
                alert("hi")
                 $scope.races = response.data;
                 }, function errorCallback(response) {
                 alert("bye");
                 $scope.error = response.statusText;
                 });
                   });
                 </script>

当我在浏览器中点击/race url 时,它总是会转到错误回调块,即使当我单独测试我的控制器时也是如此。我可以看到它从服务返回数据,但我无法获取角度 http 响应中的数据。请帮忙。

谢谢

【问题讨论】:

  • 分享您的控制台日志,显示您遇到的错误
  • 首先手动调用 REST 并从那里进行调试。
  • 使用@ResponseBody并返回数据对象而不是modelandview。
  • @SumeshTG 它是一个休息控制器

标签: java angularjs json spring spring-mvc


【解决方案1】:

如果您使用@RestController,请不要使用ModelAndView 作为任何方法的返回类型。
将您的对象保留为返回类型,spring 会将其转换为 JSON 响应。

并且ObjectMapper 不需要,因为我们不需要手动操作,Spring 会为我们完成。

所以你的控制器应该如下:

@RestController
public class RaceResultController {

    @Autowired
    RaceResultImpl raceResultImpl;

    @GetMapping("/race")
    public List<RaceTopResult>hello(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

        List<RaceTopResult> raceTopResultList = raceResultImpl.getResults();

        return raceTopResultList;


    }
}

【讨论】:

  • 谢谢我尝试了上面的方法。它没有在 angularjs 中调用 http 。它也没有在浏览器中返回 html 视图。我所看到的只是空白页面,其中包含 json 格式的数据
  • 用浏览器试试,如果你能看到对象是 JSON 响应,那么你需要启用 CORS 过滤器来从 angular 获取响应
  • @GeekStyle 实际上,您对休息和正常浏览器调用两件事感到困惑,您正在做的是对控制器的休息调用,如果只有您启用了响应体或您正在使用它,它将向您发送数据休息控制器,模型用于将数据返回到视图(jsp,thymeleaf 或任何模板引擎),视图是您的应用程序在您请求时发送给浏览器的内容。清楚地了解您要实现的目标
  • @TheSprinter 是的,我可以在浏览器中看到 json 响应,但是在启用 CORS 过滤器后,我仍然看到相同的内容..“视图”没有在浏览器中呈现
  • @JaiDixit 我需要在浏览器中渲染“视图”,即race.html,其中包含控制器返回的json数据。但实际上 json 数据正在返回到浏览器。我已将代码更改为上面 TheSprinter 提到的
【解决方案2】:

如果您希望得到 json 响应,请执行此操作

@GetMapping("/race")

    public List<RaceTopResult> hello(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

        List<RaceTopResult> raceTopResultList = raceResultImpl.getResults();
        //ObjectMapper o = new ObjectMapper();
        //model.addAttribute("races", raceTopResultList);
        return raceTopResultList;


    }

如果你在类路径中有jackson依赖,你上面的结果会自动转换成json,如果你得到任何错误在maven依赖中寻找jackson

如果你想用模型数据返回 html 视图,使用这个

@Controller //use controller not RestController
public class RaceResultController {

    @Autowired
    RaceResultImpl raceResultImpl;

    @GetMapping("/race")
    public ModelAndView hello(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {

        List<RaceTopResult> raceTopResultList = raceResultImpl.getResults();
       // ObjectMapper o = new ObjectMapper();
        model.addAttribute("races", raceTopResultList);
         return new ModelAndView(model,"race");


    }
}

【讨论】:

  • 这是一个RestController。
  • 好的,我正在编辑它,但模型中不需要发送数据:)
  • 当我只是发送数据时而不是模型..而不是将数据呈现到页面..我得到一个浏览器页面,所有数据都为 json
  • 是的,这就是它的工作原理,使用角度的 json 数据 :) @GeekStyle
  • 没有..但是race.html页面根本没有显示。显示带有 json 的空白页面
猜你喜欢
  • 1970-01-01
  • 2012-07-09
  • 2015-12-30
  • 2012-06-01
  • 1970-01-01
  • 2016-09-28
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多