---
title: "springmvc 参数传递"
author: "junner"
date: "2015-04-24T13:45:46Z"
tags: []
categories: ["企业架构"]
slug: "springmvc"
draft: false
lastmod: "2015-04-24T13:45:46Z"
id: 2205755
url: "https://junner.iteye.com/blog/2205755"
---

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&lt;String,Object&gt; 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";

}

 

       页面：

    &lt;form action="add" method="POST"&gt;

   &lt;input name="id"&gt;&lt;br/&gt;

   &lt;input name="name"&gt;&lt;br/&gt;

   &lt;input name="password"&gt;&lt;br/&gt;

   &lt;input name="nickname"&gt;&lt;br/&gt;

   &lt;input name="email"&gt;&lt;br/&gt;

   &lt;input type="submit" value="添加"&gt;

    &lt;/form&gt;

 

   注意：页面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&lt;String,Object&gt; 参数

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即可