美文网首页
深入了解@RequestParam 注解

深入了解@RequestParam 注解

作者: 意浅离殇 | 来源:发表于2017-10-15 20:43 被阅读0次

之前在控制层 一直都是采用test(String name);test(@RequestParam String name);test(@RequestParam(name="username") String name); 类似的方式赋值对这个注解了解的比较少,今天刚好有空就来深入了解一下这个注解。
首先查看一下源码

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
    @AliasFor("name")
    String value() default "";
    @AliasFor("value")
    String name() default "";
    boolean required() default true;
    String defaultValue() default ValueConstants.DEFAULT_NONE;

发现这个注解其实对应者四个方法 其中 name的别名是value,value的别名是name 用这两个注解的效果是一样的下面测试一下使用。
1.name 和value 同时使用
既然两个方法是一样的那么能一起使用么下面写一个测试用例来看下结果
定义controller

@GetMapping
    public  List<User> hello(@RequestParam(value="username",name="username") String name) {
        System.out.println(name);
        List<User> list=new ArrayList<User>();
        list.add(new  User());
        list.add(new  User());
        list.add(new  User());
        return list;
    }

定义junit

@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenQuerySuccess() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/user")
.param("username", "小明")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
}

通过测试我们发现是成功的

  1. name和value 不同名称
    修改controller
public  List<User> hello(@RequestParam(value="username",name="name") 

运行测试发现失败的 错误提示

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.core.annotation.AnnotationConfigurationException: In annotation [org.springframework.web.bind.annotation.RequestParam] declared on public java.util.List com.wen.security.controller.UserController.hello(java.lang.String) and synthesized from [@org.springframework.web.bind.annotation.RequestParam(name=name, value=username, defaultValue=                
, required=false)], attribute 'name' and its alias 'value' are present with values of [name] and [username], but only one is permitted.

发现错误only one is permitted(只允许一个名称)

  1. 众所周知当requird=false 时候即使不传这个参数也不会返回400 错误 defaultValue 当没有传这个值的时候赋一个默认值值 这个就不测试了 那么当 defaultValue 赋值默认值 并且 设置requird=true 不传参数还会不会是400错误呢
    修改controller
hello(@RequestParam(value="username",required=true,defaultValue="cxhc")

修改junit 将传参数的一行注释掉

//.param("username", "小明")

运行junit 发现测试通过了 设置了defaultValue 当设置了requird=true 即使没有传这个参数依旧可以获得默认值
文章地址:http://www.haha174.top/article/details/252060
源码地址:https://github.com/haha174/imooc-security

相关文章

网友评论

      本文标题:深入了解@RequestParam 注解

      本文链接:https://www.haomeiwen.com/subject/ttthuxtx.html