springmvc 参数传递

来源:互联网 发布:中国网络教育网 编辑:程序博客网 时间:2024/04/29 11:10
1、页面向controller传值

a、普通参数:
       表单提交,POST方法
@RequestMapping(value="login",method=RequestMethod.POST)
public String login(String username,String password){
/*
 * to do
 */
return "user";
}

       表单,或URL ?username=xxxx 提交
       ?username=成为url的一部分,没有参数会报错,要允许无参数时去掉@RequestParam("username")
        @RequestMapping("/test")
public String testMethod(@RequestParam("username") String username,Map<String,Object> context){
context.put("message",username); //map的值存在request中,页面使用
return "atest";
}

b、对象参数:

        页面提数user对象数据:
@RequestMapping(value="/add",method= RequestMethod.POST)
public String add(@ModelAttribute("user") User user){
/*
                *  to do
                */
return "redirect:/user/users";
}

       页面:
    <form action="add" method="POST">
    <input name="id"><br/>
    <input name="name"><br/>
    <input name="password"><br/>
    <input name="nickname"><br/>
    <input name="email"><br/>
    <input type="submit" value="添加">
    </form>

   注意:页面input中id,name...直接对应contorller add方法参数user对象的属性字段,而不是像struts2中在页面用user.id, user.name

c、rest风格参数传递
        如:http://localhost:8080/springmvc/user/jack  , 需要把jack作为参数传递,使用value = "/{name}" ,@PathVariable
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String show(@PathVariable String name, Model model) {
/*
               * to do
               */
return "show";
}

2、contoller处理完后,保存值页面使用

1)方法中加Map<String,Object> 参数
2)方法中加Model model参数(SpringMVC提倡的方法)
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("users", users);
return "list";
}

3)contoller中使用session
方法中加HttpSession即可

最近整理了学习材料,有需要的请下载,我放微信里面了,方便下载,还能交流,扫描我的二维码头像即可。
0 0
原创粉丝点击