笔记26 接受请求的输入 ——处理查询参数

Spring MVC允许以多种方式将客户端中的数据传送到控制器的处理器 方法中,包括:

    •   查询参数(Query Parameter)。
    •   表单参数(Form Parameter)。
    •   路径变量(Path Variable)。

首先看一下如何处理带有查询参数的请求,这也是客户端往服务器端发送数据时,最简单和最直接的方式。

在Spittr应用中,我们可能需要处理的一件事就是展现分页的Spittle列 表。在现在的SpittleController中,它只能展现最新的Spittle, 并没有办法向前翻页查看以前编写的Spittle历史记录。如果你想让用 户每次都能查看某一页的Spittle历史,那么就需要提供一种方式让用 户传递参数进来,进而确定要展现哪些Spittle集合。 

在确定该如何实现时,假设我们要查看某一页Spittle列表,这个列表 会按照最新的Spittle在前的方式进行排序。因此,下一页中第一条的 ID肯定会早于当前页最后一条的ID。所以,为了显示下一页的 Spittle,我们需要将一个Spittle的ID传入进来,这个ID要恰好小于当 前页最后一条Spittle的ID。另外,你还可以传入一个参数来确定要展现的Spittle数量。

为了实现这个分页的功能,我们所编写的处理器方法要接受如下的参数:

  • before参数(表明结果中所有Spittle的ID均应该在这个值之 前)。
  • count参数(表明在结果中要包含的Spittle数量)。 

将原来程序中的spittles()方法替换 为使用before和count参数的新spittles()方法。

1     @RequestMapping(method = RequestMethod.GET)
2     public List<Spittle> spittles(@RequestParam(value = "max", defaultValue = Long.MAX_VALUE + "") long max,
3             @RequestParam(value = "count", defaultValue = "20") int count) {
4         return spittleRepository.findSpittles(max, count);
5     }

处理器方法要同时处理有参数和没有参数的场景,那我们需要对其进行修改,让它能接受参数,同时,如果这些参数在请求中不存在的话,就使用默认值Long.MAX_VALUE和 20

注意:在设置max的默认值时会遇到一个小的问题,defaultValue的值必须是一个字符串常量,如果直接把Long.MAX_VALUE转换成字符串后还是会报错,因为不是常量,所以在这里采用Long.MAX_VALUE+“”的方法进行字符的转换。

修改测试类中的方法:

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

它针 对“/spittles”发送GET请求,同时还传入了max和count参数

原文地址:https://www.cnblogs.com/lyj-gyq/p/8933927.html