一, 从controller往视图传递值,controller—->视图
1)简单类型,如int, String,直接写在controller方法的参数里,是无法传递到视图页面上的(经测试)
2)可以用Map,其键值可以在页面上用EL表达式${键值名}得到,
3)也可以用Model类对象来传递,有addAttribute(key, value)方法,其键值可以在页面上用EL表达式${键值名}得到,
如果用addAttribute(value)这个方法,会将类型名的首字母改成小写后,作为键值名传递过去,
@RequestMapping(value="/say")
public String say(@RequestParam int id,Model model) {
System.out.println("say");
//用hello取值
model.addAttribute("hello", "value");
//使用Object的类型作为key,String-->string,用string取值
model.addAttribute("ok");
return "hello";
}
二,从视图向controller传递值, controller <— 视图
1)简单类型,如int, String, 应在变量名前加@RequestParam注解,可能放在路径里…/user?x=name
例如:
@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,效果与上面相同。还可以直接在路径中的值传过来,/user/11,用@PathVariable(“userId”)获得,用如下:
@RequestMapping(path = {"/user/{userId}"},method = {RequestMethod.GET})
public String redirect(@PathVariable("userId") String userId,Model model) {
model.addAttribute("vos",getQuestions(Integer.parseInt(userId),0,10));
return "index";
}
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对象上。