码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc请求接收参数的几种方法

时间:2016-04-18 17:07:24      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

一、通过@PathVariable获取路径中的参数

1  @RequestMapping(value="user/{id}/{name}",method=RequestMethod.GET)
2     public String printMessage1(@PathVariable String id,@PathVariable String name, ModelMap model) {
3         
4         System.out.println(id);
5         System.out.println(name);
6         model.addAttribute("message", "获取URL的参数");
7         return "users";
8  }

例如,访问user/123/hello路径时,执行以上方法,其中,参数id=123,name=hello

 

二、@ModelAttribute获取POST请求的FORM表单数据

页面表单记得加上name属性

1     <form method="post" action="hao.do">  
2      a: <input id="a" type="text" name="a"/>   
3      b: <input id="b" type="text" name="b"/>   
4      <input type="submit" value="Submit" />   
5     </form>  

用来接收的Java类:

1 public class Pojo{
2      private String a;
3      private int b;
4 
5     //setter、getter
6 }

 

Java的controller:

1 @RequestMapping(method = RequestMethod.POST) 
2 public String processSubmit(@ModelAttribute("pojo") Pojo pojo) { 
3 
4     System.out.println(pojo.getA());
5     System.out.println(pojo.getB());
6     return "helloWorld"; 
7 }

 

三、直接用HttpServletRequest获取

@RequestMapping(method = RequestMethod.GET) 
public String get(HttpServletRequest request, HttpServletResponse response) { 
    System.out.println(request.getParameter("a")); 
    return "helloWorld"; 
}

 

四、用注解@RequestParam绑定请求参数


用注解@RequestParam绑定请求参数a到变量a
当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,
例如: @RequestParam(value="a", required=false)

@RequestMapping(value = "/requestParam", method = RequestMethod.GET) 
public String setupForm(@RequestParam("a") String a, ModelMap model) { 
   System.out.println(a); 
   return "helloWorld";
}

 

springmvc请求接收参数的几种方法

标签:

原文地址:http://www.cnblogs.com/chn58/p/5405021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!