一、
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.