• 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.

  • 相关阅读:
    DS博客作业06--图
    DS博客作业05--树
    DS博客作业03--栈和队列
    DS博客作业02-线性表
    DS博客作业01--日期抽象数据类型设计与实现
    C语言博客作业06---结构体&文件
    C语言博客作业05---指针
    C语言博客作业04--数组
    DS博客作业08--课程总结
    DS博客作业07--查找
  • 原文地址:https://www.cnblogs.com/shamgod/p/5242479.html
Copyright © 2020-2023  润新知