@RequestBody
使用@RequestBody传参,@RequestBody可以传json
@Autowired
private IUserService userService;
//在需要使用日志的地方加上这句代码即可
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
//insertUser方法
@PostMapping("/insert")
public String insertUser(
@RequestBody User user
) throws Exception{
logger.info("日志 getEmail = {}",user.getMobile());
userService.insertUser(user);
return "eeee";
}
import lombok.Data;
@Data
public class User {
private int id;
private String email;
private String mobile;
private String username;
private String role;
}
在postman里填入得值:
使用此方法遇到的问题:
在spring mvc框架中需要在pom文件中加上下面的内容来引入jackson,否则接受识别不了json。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.9</version>
</dependency>
如果使用springboot,它已经自动给你引入看jackson,不需要自己去引入。springMVC就是麻烦!!!!
@RequestParam
@RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性,也可以接收application/json。
语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
value:参数名
required:是否包含该参数,默认为true,表示该请求路径中必须包含该参数,如果不包含就报错。
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值
@PostMapping("/insert")
public String insertUser(
@RequestParam(value = "id") int id,
@RequestParam(value = "email") String email,
@RequestParam(value = "username") String username,
@RequestParam(value = "role") String role,
@RequestParam(value = "mobile") String mobile
) throws Exception{
User user =new User();
user.setId(id);
user.setEmail(email);
user.setUsername(username);
user.setRole(role);
user.setMobile(mobile);
String getemail = user.getEmail();
logger.info("日志 getEmail = {}",user.getMobile());
userService.insertUser(user);
return "eee";
}
在postman里填入得值: