註解方法
在同一個控制器中,註解了@ModelAttribute
的方法實際上會在@RequestMapping
方法之前被調用。
註解無返回值方法
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
@Controller
public class HelloController {
@ModelAttribute
public void test(ModelMap model){
model.addAttribute("name","huanghaifeng");
}
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String execute(ModelMap model) {
System.out.println(model.getAttribute("name"));
return "success";
}
}
分析:test
方法將率先被調用,併爲model
添加屬性名爲name
的屬性。然後,調用execute
方法,並輸出從model
得到的屬性名爲name
的屬性。
註解有返回值的方法
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
@Controller
public class HelloController {
@ModelAttribute("name")
public String test(){
return "huanghaifeng";
}
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String execute(ModelMap model) {
System.out.println(model.getAttribute("name"));
return "success";
}
}
分析:@ModelAttribute("name")
指定了將要添加到model中的屬性的屬性名
,而該方法的返回值則是該屬性的值
。當然,也可以通過向test方法傳入model
實現以上功能。
註解方法參數變量
以上的execute
方法是通過傳入model對象
,從而獲得name屬性。實際上,通過也註解方法參數變量
實現相同功能。
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String execute(@ModelAttribute("name") String name) {
System.out.println(name);
return "success";
}
分析:註解在方法參數上的@ModelAttribute
說明了該方法參數的值將由model中取得。如果model中找不到,那麼該參數會先被實例化,然後被添加到model中。在model中存在以後,請求中所有名稱匹配的參數都會填充到該參數中。這在Spring MVC
中被稱爲數據綁定,一個非常有用的特性,節約了你每次都需要手動從表格數據中轉換這些字段數據的時間。
@ModelAttribute和@RequestMapping同時註釋一個方法
@Controller
public class HelloWorldController {
@RequestMapping(value = "/helloWorld")
@ModelAttribute("attributeName")
public String helloWorld() {
return "hey";
}
}
分析:這裏必須要知道,此時該方法的返回值不是視圖名
,而是屬性的值
。