三个常用注解:
@RequestParam、@RequestBody、 @PathVariable、
1.@RequestParam:将请求参数绑定到你控制器的方法参数上(是springmvc中接收普通参数的注解)
例如:URL:localhost:8080/del?id=3
@ResponseBody
@GetMapping("/del")
public String deleteUserByIdOneContorller(@RequestParam("id") int id){
boolean resulte = userService.deleteUserByIdOne(id);
if (resulte){
return "删除成功";
}
return "删除失败!";
}
2.@PathVariable可以用来映射URL中的占位符到目标方法的参数中
例如:URL:localhost:8080/findSpecsByPhoneId/3
@GetMapping("/findSpecsByPhoneId/{phoneId}")
public ResultVO findSpecsByPhoneId(@PathVariable("phoneId") Integer phoneId){
return ResultVOUtil.success(phoneService.findSpecsByPhoneId(phoneId));
}
3、通过HttpServletRequest接收,post方式和get方式都可以。
@RequestMapping("/addUser2")
public String addUser2(HttpServletRequest request) {
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
4. 用注解@RequestBody绑定请求参数到方法入参 用于POST请求,UserDTO 这个类为一个实体类,里面定义的属性与URL传过来的属性名一一对应。
@RequestMapping(value="/addUser6",method=RequestMethod.POST)
public String addUser6(@RequestBody UserDTO userDTO) {
System.out.println("username is:"+userDTO.getUserName());
System.out.println("password is:"+userDTO.getPassWord());
return "demo/index";
}
5.直接把表单的参数写在Controller相应的方法的形参中,提交的参数需要和Controller方法中的入参名称一致。
例如:URL:http://localhost/SSMDemo/demo/addUser1?username=lixiaoxi&password=111111
public String addUser1(String username,String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
6.通过一个bean来接收,post方式和get方式都可以。
(1)建立一个和表单中参数对应的bean
public class UserModel {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
(2)用这个bean来封装接收的参数
@RequestMapping("/addUser3")
public String addUser3(UserModel user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "demo/index";
}
7.使用@ModelAttribute