Spring注解-@ModelAttribute

适用范围

  • 方法
  • 参数

标注在方法上

@ModelAttribute标注在方法上时表明这个方法是用于给Model模型添加一个或多个属性。
标注了@ModelAttribute的方法会在访问@RequestMapping方法前先执行(同一个类中),这个方法通常用于参加通用的属性。
一个类中可以有任意个@ModelAttribute标注的方法,它们都会在这个类的@RequestMapping方法前执行
例子:

//某个Controller中的方法
    @ModelAttribute
    public Version getVersion(){
        return new Version();
    }
    @RequestMapping("/one")
    public String show(){
        return "testmodelattr";
    }

testmodelattr.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <p> ${version } </p>
</body>
</html>

这样,当我们访问/one时,标注了@ModelAttribute的getVersion方法会被执行,上面这种写法会以(“返回类型(首字母小写)”,“返回值”)的形式添加一个属性在Model中,效果等同于在@RequestMapping为Model装配了一个属性,在这里向Model中添加了(“version”, new Version()).于是我们在testmodelattr.jsp可以得到version属性的值。
我们也可以显示的设定属性的名称,在@ModelAttribute添加value属性:@ModelAttribute(“myversion”).这样,在jsp中就可以通过$(myversion)访问。
也可以直接在标注了@ModelAttribute的方法上添加一个Model参数,直接为这个参数添加属性和值。也可以达到同样的效果,并且可以配置多个属性。

@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
    model.addAttribute(accountManager.findAccount(number));//没有指定名称默认为类型名,首字母小写
    model.addAttribute("modelname", value);
    // add more ...
}

标注了@ModelAttribute的方法同时也可以标注@RequestMapping方法,只此时方法的返回值将不是解析成视图,而是Model的属性值。视图名将会通过RequestToViewNameTranslator解析。

标注在方法参数上

待续

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值