您的位置:首页 > 编程语言 > Java开发

Spring DataBinding

2015-08-06 11:26 429 查看
1. 用@ModelAttribute注释方法

1.1
@ModelAttribute和@RequestMapping同时注释一个方法

<span style="font-size:14px;">    @RequestMapping(method = RequestMethod.GET)
@ModelAttribute
public Account register(Locale currentLocale) {
Account account = new Account();
account.getAddress().setCountry(currentLocale.getCountry());
return account;
}</span>

这个方法的返回值不是视图名称,而是model属性的值。视图名称由RequestToViewNameTranslator根据请求转换为逻辑视图。

Model属性名称有@ModelAttribute(value="")指定,相当于在request中封装了key="account" , value=account。

2. 用@ModelAttribute注释方法参数

@ModelAttribute
public BookSearchCriteria criteria() {
return new BookSearchCriteria();
}

@ModelAttribute("categories")
public List<Category> getCategories() {
return this.bookstoreService.findAllCategories();
}

/**
* This method searches our database for books based on the given {@link BookSearchCriteria}.
* Only books matching the criteria are returned.
*
* @param criteria the criteria used for searching
* @return the found books
*
* @see com.apress.prospringmvc.bookstore.repository.BookRepository#findBooks(BookSearchCriteria)
*/
@RequestMapping(value = "/book/search", method = { RequestMethod.GET })
public Collection<Book> list(@ModelAttribute("bookSearchCriteria") BookSearchCriteria criteria) {
return this.bookstoreService.findBooks(criteria);
}
@ModelAttribute("bookSearchCriteria")
BookSearchCriteria criteria注释方法参数,参数criteria的值来源于criteria()方法中的model属性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: