SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

一、

1.Spring MVC provides several ways that a client can pass data into a controller’s handler method. These include

 Query parameters
 Form parameters
 Path variables

 

二、以query parameters的形式给action传参数

1.传参数

 

 1 @Test
 2   public void shouldShowPagedSpittles() throws Exception {
 3     List<Spittle> expectedSpittles = createSpittleList(50);
 4     SpittleRepository mockRepository = mock(SpittleRepository.class);
 5     when(mockRepository.findSpittles(238900, 50))
 6         .thenReturn(expectedSpittles);
 7     
 8     SpittleController controller = new SpittleController(mockRepository);
 9     MockMvc mockMvc = standaloneSetup(controller)
10         .setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
11         .build();
12 
13     mockMvc.perform(get("/spittles?max=238900&count=50"))
14       .andExpect(view().name("spittles"))
15       .andExpect(model().attributeExists("spittleList"))
16       .andExpect(model().attribute("spittleList", 
17                  hasItems(expectedSpittles.toArray())));
18   }

 

 

 

2.controller接收参数

(1).

@RequestMapping(method = RequestMethod.GET)
public List < Spittle > spittles(
    @RequestParam("max") long max,
    @RequestParam("count") int count) {
    return spittleRepository.findSpittles(max, count);
}

 

(2).设置默认值

 

1 private static final String MAX_LONG_AS_STRING = Long.toString(Long.MAX_VALUE);
2 
3 @RequestMapping(method = RequestMethod.GET)
4 public List < Spittle > spittles(
5     @RequestParam(value = "max",defaultValue = MAX_LONG_AS_STRING) long max,
6     @RequestParam(value = "count", defaultValue = "20") int count) {
7     return spittleRepository.findSpittles(max, count);
8 }

 

Because query parameters are always of type String , the defaultValue attribute requires a String value. Therefore, Long.MAX_VALUE won’t work. Instead, you can capture Long.MAX_VALUE in a String constant named MAX_LONG_AS_STRING :

private static final String MAX_LONG_AS_STRING = Long.toString(Long.MAX_VALUE);

Even though the defaultValue is given as a String , it will be converted to a Long when bound to the method’s max parameter.

posted @ 2016-03-04 16:12  shamgod  阅读(7078)  评论(0编辑  收藏  举报
haha