SpringMVC中Controller接受参数的几种方式

1.@RequestParam注解可以获取请求的参数

 
 
@RequestMapping("/get")
public ModelAndView get(@RequestParam("id") Integer id){
...
}

例如通过以上方式,在Controller的方法参数中使用@RequestParam("id")注解就可以获取请求中的id属性值,并赋给入参的Integer类型的id。


2.@SessionAttribute注解可以获取Session域中的参数

@RequestMapping("/get")
public ModelAndView get(@SessionAttribute("user") User user){
...
}

例如以上用法,可以通过在方法参数中使用@SessionAttribute("user")注解就可以获得session域中名为user的对象并赋给类型为User 的user


3.@PathVariable注解可以获取URL中的参数

@RequestMapping("/get/{id}")
public ModelAndView get(@PathVariable("id") Integer id){
...
}

以上用法就是使用@PathVariable("id")注解来获取请求URL路径“/get/{id}”中的id值,例如URL 为“/get/2”,则会把2赋给Integer类型的id。

4.@RequestAttribute注解可以获得request域中的属性值

例如在jsp等页面中,或在其他Controller方法中在request域中保存了值

request.setAttribute("id",1);

则可以通过如下方式取得

@RequestMapping("/get")
public ModelAndView get(@RequestAttribute("id") Integer id){
...
}


猜你喜欢

转载自blog.csdn.net/qq_40995335/article/details/80683739