springboot服务端获取前端传递的参数
1、直接把参数写在Controller相应的方法的形参中
@RequestMapping("a")
public void tta(String name,String password) {
String tName = name;
String tPassword= password;
System.out.println("形参测试:"+tName+","+tPassword);
}
调用接口传参: http://localhost:8080/a?name=123&password=456
2、使用HttpServletRequest接收参数
@RequestMapping("b")
public void ttb(HttpServletRequest httpServletRequest) {
String tName = httpServletRequest.getParameter("name");
String tPassword= httpServletRequest.getParameter("password");;
System.out.println("HttpServletRequest测试"+tName+","+tPassword);
}
调用接口传参: http://localhost:8080/b?name=456&password=789
3、使用bean来接收参数
建一个bean类对应接收的参数
package com.example.demo;
public class User {
String name;
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
调用bean接收参数
@RequestMapping(value = "c")
public void ttc(User user) {
String tName = user.getName();
String tPassword= user.getPassword();
System.out.println("bean测试"+tName+","+tPassword);
}
调用接口传参:
4、通过@PathVariable获取参数
这种传参方式是以路径的方式传参
@RequestMapping(value = "d/{name}/{password}")
public void ttd(@PathVariable String name, @PathVariable String password) {
String tName = name;
String tPassword= password;
System.out.println("@PathVariable测试"+tName+","+tPassword);
}
调用接口传参: http://localhost:8080/d/2/3
5、使用@ModelAttribute注解获取参
@RequestMapping(value = "e")
public void tte(@ModelAttribute User user) {
String tName = user.getName();
String tPassword= user.getPassword();
System.out.println("@ModelAttribute测试"+tName+","+tPassword);
}
调用接口传参
6、用注解@RequestParam绑定请求参数到方法入参
这种方式默认是required = true
,必须传对应的参数,不然会报错,可以改成required = false
@RequestMapping(value = "f")
public void ttf(@RequestParam(required = true) String name, @RequestParam String password) {
String tName = name;
String tPassword = password;
System.out.println("@RequestParam测试" + tName + "," + tPassword);
}
调用接口传参:
7、使用@RequestBody获取参数
这种方式主要用于接收json数据类型
@RequestMapping(value = "g")
public void ttg(@RequestBody User user) {
String tName = user.getName();
String tPassword= user.getPassword();
System.out.println("@RequestBody测试" + tName + "," + tPassword);
}
调用接口传参