[英]Spring Controller not returning JSON data to angular http GET call
我有一個看起來像這樣的彈簧控制器:
@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響應中獲取數據。 請幫忙。
謝謝
如果您想找回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;
}
如果您在類路徑中具有傑克遜依賴關系,則您的上述結果將自動轉換為json,如果遇到任何錯誤,請在maven依賴關系中查找傑克遜
如果您想獲取帶有模型數據的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
不要將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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.