我使用了Thymeleaf作为模板引擎,在Controller层中,使用request对象存储一个值并传递到前端页面
,在前端页面获取request中的值。
一开始,我的Controller层是这么写的:
@RequestMapping("/getgoodsinfo")
public String getGoodsInfo(@RequestParam("xx") String goodsId,HttpServletRequest request){
Goods goods = goodsService.findGoodsInfoByGoodsId(goodsId);
if(goods == null){
System.out.println("系统出现异常!");
return "error";
}else{
System.out.println(goods);
request.setAttribute("modifygoodsinfo", goods);
return "goodsitemmodify";
}
}
但是这样,在前端无论如何都取不出request中的modifygoodsinfo的值:
<div th:object="${modifygoodsinfo}">//这个位置会飘红报错
......
</div>
然后我就将Controller层更改为使用ModelAndView:
@RequestMapping("/getgoodsinfo")
public ModelAndView getGoodsInfo(@RequestParam("xx") String goodsId,HttpServletRequest request){
Goods goods = goodsService.findGoodsInfoByGoodsId(goodsId);
ModelAndView mv = new ModelAndView();
if(goods == null){
System.out.println("系统出现异常!");
mv.setViewName("error");
return mv;
}else{
System.out.println(goods);
mv.addObject("modifygoodsinfo", goods);
mv.setViewName("goodsitemmodify");
return mv;
}
}
在前端就能够获取到了:
<div th:object="${modifygoodsinfo}">//这个位置没有飘红报错
......
</div>
为什么使用request不行,但是使用ModelAndView却可以呢?ModelAndView我理解的是和request一样的,只不过它还能够转发视图,这样理解不正确是吗?