Spring MVC3在controller和视图之间传递参数的方法:

一, 从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对象上。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值