欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
Spring Boot 获取URL请求参数的方法
1. 通过 @RequestParam 注解获取 url 参数
url格式:http://localhost/adduser?username=aizws&password=88888
@GetMapping("/adduser")
public String addUser(@RequestParam("username") String username,@RequestParam("password") String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "username is:"+username + " " + "password is:"+password;
}
2. 把 url 参数写在 Controller 相应的方法的形参中
url格式:http://localhost/adduser?username=aizws&password=88888
// 注意方法中的参数名要与url中携带的参数名一样
@RequestMapping("/adduser")
public String addUser(String username,String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "username is:"+username + " " + "password is:"+password;
}
3. 通过 HttpServletRequest 接收参数
url格式:http://localhost/adduser?username=aizws&password=88888
@RequestMapping("/adduser")
public String addUser(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 "username is:"+username + " " + "password is:"+password;
}
4. 通过 bean 接收参数
url格式:http://localhost/adduser?username=aizws&password=88888
bean:
// 注意这里类的属性名要和url请求携带的参数名一样
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;
}
}
用这个bean来封装接收的参数:
@RequestMapping("/adduser")
public String addUser(UserModel user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "username is:"+username + " " + "password is:"+password;
}
下一章:Spring Boot 获取URL路径参数的方法
Spring Boot 通过 @PathVariable 注解获取 Url 路径参数。我们可以将 URL 中占位符参数绑定到控制器处理方法的参数:1. 在 @GetMapping 或者 @R ...
AI 中文社