将表单中的值封装成JavaBean对象的疑惑
老师,在本节视频介绍了用注解方式实现SpringMVC开发的小案例,这里是通过一个表单,表单填写好后直接发送请求到指定路径的后台,在这个路径对应的Handler处理中,发现直接把表单的数据当成封装好的对象来使用了,请问这么做的原理是什么?
在学SpringMVC之前,在Servlet中,我们都是把表单请求到的数据手动封装到一个JavaBean对象中的,为什么之前不可以直接把表单数据当成一个封装好的JavaBean对象直接使用么?
相关代码如图:
表单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | < form class = "form-horizontal" role = "form" action = "addGoods" method = "post" > < div class = "form-group" > < label class = "col-sm-1 control-label" >名称</ label > < div class = "col-sm-3" > < input type = "text" class = "form-control" name = "name" placeholder = "请输入商品名称" > </ div > </ div > < div class = "form-group" > < label class = "col-sm-1 control-label" >价格</ label > < div class = "col-sm-3" > < input type = "text" class = "form-control" name = "price" placeholder = "请输入商品价格" > </ div > </ div > < div class = "form-group" > < div class = "col-sm-offset-1 col-sm-3" > < button type = "submit" class = "btn btn-default" >提交</ button > </ div > </ div > </ form > |
表单处理:
1 2 3 4 5 6 7 8 9 10 11 | /** * 添加商品并展示 */ @RequestMapping ( "/addGoods" ) public ModelAndView addGoods(Goods goods){ System.out.println(goods.getName()+ "---" +goods.getPrice()); ModelAndView modelAndView= new ModelAndView(); modelAndView.addObject( "goods" ,goods); modelAndView.setViewName( "show" ); return modelAndView; } |
6
收起
正在回答
1回答
你好!这个把表单数据自动封装成JavaBean,可以说是SpringMVC的便捷之处,它的底层将这些操作都做了,为开发提供了方便。而之前的Servlet是没有这个功能的,需要我们自己完成。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
4. SSM到Spring Boot入门与综合实战
- 参与学习 人
- 提交作业 323 份
- 解答问题 8263 个
本阶段将带你学习主流框架SSM,以及SpringBoot ,打通成为Java工程师的最后一公里!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧