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

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

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

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

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

页面表单记得加上name属性

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

用来接收的Java类:

 public class Pojo{
private String a;
private int b; //setter、getter
}

Java的controller:

 @RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pojo") Pojo pojo) { System.out.println(pojo.getA());
System.out.println(pojo.getB());
return "helloWorld";
}

三、直接用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";
}
上一篇:【转】Java提高篇(三四)-----fail-fast机制


下一篇:SoapUI接口测试之JDBC(三)