问题:SSM前端jsp页面使用angular请求数据,后台Controller拿到了数据但是个别值是空的,因此报了此异常。
原来我懒得在controller封装json数据,直接使用的是第一种方式转换:
// 前端angular请求数据
@ResponseBody
@RequestMapping(value="showCar", method = RequestMethod.POST)
public JSONArray showCar(@RequestBody(required=false)String requestJson,HttpSession session) {
System.out.println("CarController.showCar() ran...");
// 从session中拿到UserId
Integer userId = (Integer) session.getAttribute("uId");
System.out.println("从session中拿到的UserId:;"+userId);
Car car = this.carService.findByUserId(userId);
List<CarItem> carItemList = car.getCarItem();
System.out.println("找到用户的购物车:");
System.out.println(car);
// 第一种方式:car直接转为json格式
// JSONArray jsonCar = JSONArray.fromObject(car);
// 第二种:
JSONArray json = new JSONArray();
for(CarItem item : carItemList){
JSONObject jo = new JSONObject();
jo.put("trainName", item.getCaritemTrainName());
jo.put("trainPrice",item.getCaritemTrainPrice());
jo.put("trainImg", item.getCaritemTrainImg());
jo.put("trainCheck", item.getCaritemChecked());
json.element(jo);
System.out.println("JSONArray json==="+json);
System.out.println(" JSONObject jo==="+jo);
}
return json;
}
然后一直异常,jsp检查了好久
解决:后面就换成了第二种方式:前端需要啥我就装啥进去。。。
然后前端就拿到了
<script>
var app=angular.module("userCarApp" , [])
app.controller("myCar",function($scope,$http){
$http({
method : "POST",
url : "http://localhost:8080/car/showCar"
}).then(function(response) {
$scope.car=response.data
});
})
</script>
感谢大神!参考自:https://blog.csdn.net/a954735254/article/details/81670695
不过有一个地方:
JSONArray 对象 里面要装JSONObject对象的时候, 我用上面的博客的put方法,但是不可行,可能是版本问题吧,我猜的
我的版本:
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
因此不用put(),改成:element()
json.element(jo);