700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > springMVC Controller层接收 JSON参数遇到得问题

springMVC Controller层接收 JSON参数遇到得问题

时间:2019-04-07 19:05:47

相关推荐

springMVC Controller层接收 JSON参数遇到得问题

@RequestBody

使用@RequestBody传参,@RequestBody可以传json

@Autowiredprivate 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;@Datapublic 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里填入得值:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。