之前在控制層 一直都是采用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));
}
通過測試我們發現是成功的
- 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(只允許一個名稱)
- 眾所周知當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