spring mvc获取路径参数的几种方式

时间:2023-03-09 09:33:56
spring mvc获取路径参数的几种方式

一、从视图向controller传递值,  controller <--- 视图

1、通过@PathVariabl注解获取路径中传递参数 (参数会被复制到路径变量)

 @RequestMapping(value = "/{id}/{str}")
public ModelAndView helloWorld(@PathVariable String id,
@PathVariable String str) {
System.out.println(id);
System.out.println(str);
return new ModelAndView("/helloWorld");
}

2、  
 
1)简单类型,如int, String, 应在变量名前加@RequestParam注解,
例如:

@RequestMapping("hello3")
public String hello3( @RequestParam("name" ) String name,
@RequestParam("hobby" ) String hobby){
System. out.println("name=" +name);
System. out.println("hobby=" +hobby);
return "hello" ;
}

  但这样就要求输入里面必须有这两个参数了,可以用required=false来取消,例如:
@RequestParam(value="name",required=false) String name
但经测试也可以完全不写这些注解,即方法的参数写String name,效果与上面相同。

2)对象类型:

@RequestMapping("/hello4" )
public String hello4(User user){
System.out.println("user.getName()=" +user.getName());
System.out.println("user.getHobby()=" +user.getHobby());
return "hello";
}

  Spring MVC会按:
     “HTTP请求参数名=  命令/表单对象的属性名”
    的规则自动绑定请求数据,支持“级联属性名”,自动进行基本类型数据转换。
此外,还可以限定提交方法为POST,即修改方法的@RequestMapping注解为
@RequestMapping(value="/hello4",method=RequestMethod.POST)