0

I have a spring controller which looks like this:

@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");


    }
}

Then I have some embedded angular code in my view 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>

When I'm hitting /race url in the browser, it always goes to the error callback block, even though when I test my controller separately. I can see it returns data from the service, but I cannot get the data in angular http response. Please help.

Thanks

common sense
  • 3,775
  • 6
  • 22
  • 31
GeekStyle
  • 13
  • 1
  • 9

2 Answers2

1

If you are looking to get the json reponse back do this

@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;


    }

If you have a jackson dependency in class path ,your result above will automatically be turned into json,if you get any error look for jackson in maven dependency

If you want to get the html view back with model data use this

@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");


    }
}
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
1

If you are using @RestController dont use ModelAndView as return type of your any of the methods.
Keep your object as return type and spring will convert that to JSON response.

and ObjectMapper is not needed as we are not doing manually, Spring will do for us.

So your Controller should be as below:

@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;


    }
}
TheSprinter
  • 1,523
  • 17
  • 30
  • Thanks I tried the above..it doesn't hit the http call inside angularjs..And it doesn't return the html view in the browser as well. All I see is as blank page with data in json format – GeekStyle Dec 14 '18 at 11:32
  • try with browser, if you are able to see object as JSON response, then you need to enable CORS filter to get response from angular – TheSprinter Dec 14 '18 at 11:33
  • @GeekStyle actually you are confused regarding two things rest and normal browser call ,what you are doing is rest call to the controller it will send data back to you if only you have responsebody enabled or you are using rest controller ,Model is for returning data to the view (jsp ,thymeleaf or any template engine) ,view is what your application sends to the browser when you request it .Get a clear picture of what you are trying to achieve – Shubham Dixit Dec 14 '18 at 11:56
  • @TheSprinter yes I am able to see the json response in the browser but after enabling the CORS filter, I still see the same..The "view" is not getting rendered in browser – GeekStyle Dec 14 '18 at 12:01
  • @JaiDixit I need to render the "view" which is race.html in the browser with the json data returned by controller inside it. but in real the json data is being returned to the browser. I have changed the code to as mentioned by TheSprinter above – GeekStyle Dec 14 '18 at 12:03
  • @GeekStyle if you are getting response from browser then only CORS needs to be modified , please refer the url https://stackoverflow.com/questions/32319396/cors-with-spring-boot-and-angularjs-not-working and https://stackoverflow.com/questions/40286549/spring-boot-security-cors – TheSprinter Dec 14 '18 at 12:10
  • @GeekStyle but then there is no reason to send the http request to the controller ,remove rest controller ,use normal controller ,return data in modal ,iterate over the data through angular in your view ,and you cant access the modal data in the html unless you are using thymeleaf or any other templating engine ,or use jsp ! – Shubham Dixit Dec 14 '18 at 12:22