[SSM]Spring MVC3在controller和檢視之間傳遞引數的方法
Spring MVC3在controller和檢視之間傳遞引數的方法:
一, 從controller往檢視傳遞值, controller—->檢視
1)簡單型別,如int, String,直接寫在controller方法的引數裡,是無法傳遞到檢視頁面上的(經測試)。
(而用@RequestParam("name")
註解,可以從檢視上,或地址中加?name=***
傳遞到controller方法裡)
2)可以用Map<String, Object>
,其鍵值可以在頁面上用EL表示式${鍵值名}得到,
3)也可以用Model類物件來傳遞,有addAttribute(key, value)方法,其鍵值可以在頁面上用EL表示式${鍵值名}得到,
如果用addAttribute(value)這個方法,會將型別名的首字母改成小寫後,作為鍵值名傳遞過去,例如”ok”在頁面上用${string}
得到,而一個複合類物件,如User類物件,頁面上用${user}
得到該物件,用${user.propertyName}
得到其屬性,這是用Model的一大優勢。
例如,model.addAttribute(new User("my姓名","我的愛好有游泳打球"));
這樣頁面上就能用${user.name}
和${user.hobby}
列印對應屬性
@RequestMapping(value={"/","/hello"})
public String hello(int id,Map<String,Object> map) {
System.out.println(id);
System.out.println("hello");
map.put("hello", "world");
return "hello";
}
@RequestMapping(value="/say")
public String say(@RequestParam int id,Model model) {
System.out .println("say");
model.addAttribute("hello", "value");
//使用Object的型別作為key,String-->string
model.addAttribute("ok");
return "hello";
}
二,從檢視向controller傳遞值, controller <— 檢視
1)簡單型別,如int, String, 應在變數名前加@RequestParam註解,
例如:
@RequestMapping("hello3")
public String hello3( @RequestParam("name" ) String name,
@RequestParam("hobby" ) String hobby){
System. out.println("name=" +name);
System. out.println("hobby=" +hobby);
return "hello" ;
}
但這樣就要求輸入裡面必須有這兩個引數了,可以用required=false來取消,例如:
@RequestParam(value="name",required=false) String name
但經測試也可以完全不寫這些註解,即方法的引數寫String name,效果與上面相同。
2)物件型別:
@RequestMapping("/hello4" )
public String hello4(User user){
System.out.println("user.getName()=" +user.getName());
System.out.println("user.getHobby()=" +user.getHobby());
return "hello";
}
Spring MVC會按:
“HTTP請求引數名 = 命令/表單物件的屬性名”
的規則自動繫結請求資料,支援“級聯屬性名”,自動進行基本型別資料轉換。
即有一個User類,如下
package model;
public class User {
private String name ;
private String hobby ;
public User(){
}
public User(String name, String hobby) {
this.name = name;
this.hobby = hobby;
}
//...get/set方法略
則頁面上可以用
<form name="form1" action="hello4" method="post">
<input type="text" name="name"/>
<input type="text" name="hobby"/>
...
提交後,把值直接繫結到user物件上。
此外,還可以限定提交方法為POST,即修改方法的@RequestMapping註解為
@RequestMapping(value="/hello4",method=RequestMethod.POST)
最後,注意,如果這裡提交過來的字元出現亂碼,應該在web.xml里加入如下filter:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name >
<url-pattern>/*</url-pattern>
</filter-mapping>