ITeye博客

springmvc 参数传递

junner · 2015-04-24 13:45 · Spring · 企业架构 · Markdown

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。