栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

@ModelAttribute批注,何时使用?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@ModelAttribute批注,何时使用?

您不需要仅使用Bean作为参数的

@ModelAttribute
parameter

例如,这些处理程序方法可以很好地处理以下请求:

@RequestMapping("/a")void pathA(SomeBean someBean) {  assertEquals("neil", someBean.getName());}GET /a?name=neil@RequestMapping(value="/a", method=RequestMethod.POST)void pathAPost(SomeBean someBean) {  assertEquals("neil", someBean.getName());}POST /aname=neil

使用

@ModelAttribute
方法 )将每个请求的 默认数据
加载到模型中,例如从数据库中加载,尤其是使用时
@SessionAttributes
。这可以在
Controller
或中完成
ControllerAdvice

@Controller@RequestMapping("/foos")public class FooController {  @ModelAttribute("foo")  String getFoo() {    return "bar";  // set modelMap["foo"] = "bar" on every request  }}

FooController
以下任何转发到的JSP :

${foo} //=bar

要么

@ControllerAdvicepublic class MyGlobalData {  @ModelAttribute("foo")  String getFoo() {    return "bar";  // set modelMap["foo"] = "bar" on every request  }}

任何JSP:

${foo} //=bar

如果要使用( 方法* )的结果作为 默认值, 请使用

@ModelAttribute
参数 ):
@ModelAttribute


* __

@ModelAttribute("attrib1")SomeBean getSomeBean() {  return new SomeBean("neil");  // set modelMap["attrib1"] = SomeBean("neil") on every request}@RequestMapping("/a")void pathA(@ModelAttribute("attrib1") SomeBean someBean) {  assertEquals("neil", someBean.getName());}GET /a

使用

@ModelAttribute
参数 )获取存储在 flash属性中 的对象:

@RequestMapping("/a")String pathA(RedirectAttributes redirectAttributes) {  redirectAttributes.addFlashAttribute("attrib1", new SomeBean("from flash"));  return "redirect:/b";}@RequestMapping("/b")void pathB(@ModelAttribute("attrib1") SomeBean someBean) {  assertEquals("from flash", someBean.getName());}GET /a

使用

@ModelAttribute
参数 )获取存储的对象
@SessionAttributes

@Controller@SessionAttributes("attrib1")public class Controller1 {    @RequestMapping("/a")    void pathA(Model model) {        model.addAttribute("attrib1", new SomeBean("neil")); //this ends up in session due to @SessionAttributes on controller    }    @RequestMapping("/b")    void pathB(@ModelAttribute("attrib1") SomeBean someBean) {        assertEquals("neil", someBean.getName());    }}GET /aGET /b



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/435472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号