springmvc方法参数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chang_li/article/details/82811726

1、接收普通请求参数

在没有任何注解的情况下,springmvc可以通过参数名称和http请求参数的名称保持一致来获取参数;

@RequestMapping("/commonParams")
public ModelAndView commonParams(String roleName, String note) {}

2、javabean接收http参数

@RequestMapping("/commonParamPojo")
public ModelAndView commonParamPojo(RoleParams roleParams) {}

3、@RequestParam

springmvc提供@RequestParam映射http参数名称,默认情况下该参数不能为空,如果为空系统会抛出异常。
如果希望允许它为空,就要修改配置项required为false

@RequestParam(value="role_name",required=false) String roleName

4、使用url传递参数

需要@RequestMapping和@PathVariable两个注解共同协作完成,访问/param/getRole/1

@RequestMapping("/getRole/{id}")
public ModelAndView pathVariable(@PathVariable("id") Long id)  {}

5、传递json参数

@RequestBody接收参数,该注解表示要求springmvc将传递过来的json数组数据转换为对应的java集合类型。
把list转换为数组也是可行的。

@RequestMapping("/findRoles")
public ModelAndView findRoles(@RequestBody RoleParams roleParams) {}
@RequestMapping("/deleteRoles")
public ModelAndView deleteRoles(@RequestBody List<Long> idList) {}
@RequestMapping("/addRoles")
public ModelAndView addRoles(@RequestBody List<Role> roleList) {}

curl命令发送请求测试

curl -XPOST 'http://localhost:8080/javabean/save.json' -H 'Content-Type:application/json' -d'{"name":"hello","id":1}'

6、MultipartFile处理文件上传

@PostMapping("form)
public String handleFileUpload(String name,MultipartFile file)throws IOException{
	if(!file.isEmpty()){
		String filename = file.getOriginalFilename();//获取上传的文件名
	}
}

如果上传多个文件

@PostMapping("form)
public String handleFileUpload(String name,MultipartFile[] files)throws IOException{}

7、@ModelAttribute

该注解通常可以用来向一个controller中需要的公共模型添加数据。

@ModelAttribute
public void findUserById(@PathVariable Long id,Model model){
	model.addAttribute("user",userService.getUserById(id));
}

如果只添加一个对象到model中,可以改写为

@ModelAttribute
public User findUserById(@PathVariable Long id){
	return userService.getUserById(id);
}
@GetMapping(path="/{id}/get.json")
public String getUser(Model model){
	return "success";
}

8、Model/ModelAndView

MVC框架一般都会提供一个类似Map结构的Model,可以向model中添加视图需要的变量,springmvc提供addAttribute(String attributeName,Object attributeValue)
Model用于参数的时候,SpringMvc框架在调用方法前自动创建Model

@GetMapping(path = "/{userId}/get.html")
public String getUser(@PathVariable Long userId,Model model){
	modle.addAttribute("user",userInfo);
	return "userInfo.html";
}

ModelAndView类似于Model,但还提供了一个视图名称,该对象既可以通过方法声明,也可以在方法中构造

@GetMapping(path = "/{userId}/get.html")
public String getUser(@PathVariable Long userId,ModelAndView modelAndView){
	modelAndView.addObject("user",userInfo);
	modelAndView.setViewName("/userInfo.html");
	return view;
}

@GetMapping(path = "/{userId}/get.html")
public String getUser(@PathVariable Long userId){
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addObject("user",userInfo);
	modelAndView.setViewName("/userInfo.html");
	return view;
}

猜你喜欢

转载自blog.csdn.net/chang_li/article/details/82811726