前后端的传参与接参:
前端传参:
1、url传参
-
?传参
http(s): //域名/项目名/接口名?key1=value1&key2=value2 -
restful风格
http(s): //域名/项目名/接口名/value1/value2(这种方法传的参数不是键值对)
2、表单传参
-
action : 传参的地址
-
method : 传参的方式,get/post
-
enctype: 上传文件的格式 multipart/form-data
3、Json传参
后端接参:
1、直接把表单的参数写在Controller相应的方法的形参中,适用于GET 和 POST请求方式。
@RestController
@RequestMapping("/test")
public class testController {
@RequestMapping("/login")
public String login(String username,String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "success";
}
}
2、通过HttpServletRequest接收,适用于GET 和 POST请求方式。
@RestController
@RequestMapping("/test")
public class testController {
@RequestMapping("/login")
public String login(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 "success";
}
}
3、用注解@RequestParam绑定请求参数到方法入参,适用于GET 和 POST请求方式。
@RestController
@RequestMapping("/test")
public class testController {
@RequestMapping("/login")
public String login(@RequestParam("username") String username,@RequestParam("password") String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "success";
}
}
4、用注解@PathVariable接受rest风格请求参数到方法入参 ,适用于GET 和 POST请求方式。
@RestController
@RequestMapping("/test")
public class testController {
@RequestMapping("/login/{username}/{password}")
public String login(@PathVariable("username") String username,@PathVariable("password") String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "success";
}
}
5、用注解@RequestBody绑定请求参数到方法入参 ,用于POST请求。
@RestController
@RequestMapping("/test")
public class InnerController {
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@RequestBody User user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "success";
}
}