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.传参数

 @Test
public void shouldShowPagedSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(50);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(238900, 50))
.thenReturn(expectedSpittles); SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build(); mockMvc.perform(get("/spittles?max=238900&count=50"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
}

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).设置默认值

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

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

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.

上一篇:Oozie分布式工作流——从理论和实践分析使用节点间的参数传递


下一篇:SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-003编写JPA-based repository( @PersistenceUnit、 @PersistenceContext、PersistenceAnnotationBeanPostProcessor)