0

spring | @RequestParam

 1 year ago
source link: https://benpaodewoniu.github.io/2023/01/30/spring40/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

spring | @RequestParam

@RequestParam 总体上来说,该注解类拥有三个参数:

  • valuename 属性都标识请求参数名(必须配置);
  • required:参数是否必传,默认为 true,可以设置为非必传 false;(如果设置了必传或默认,请求未传递参数,将会抛出异常);
  • defaultValue:参数默认值,如果设置了该值,required 将会自动设置为 false

Spring 中的 @RequestParam 注解接收的参数大多数场景是来自 requestHeaders 中,即请求头,也就是 url 中,格式为:http://localhost:8080?name=yc&age=23,由于 url 长度有限制,所以参数需要限制数量和值得长度;

@RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(@RequestParam("id") Integer id,
@RequestParam("name") String name,
@RequestParam("age") Integer age) {
log.info("id = {}, name = {}, age = {}", id, name, age);
}
id = 1, name = yc, age = 23

不使用 @RequestParam 注解直接进行对象属性赋值

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
}

@RequestMapping(value = "/test", method = RequestMethod.GET)
public void test(User user) {
log.info("id = {}, name = {}, age = {}", user.getId(), user.getName(), user.getAge());
}
id = 1, name = yc, age = 23

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK