zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    本来一行可以代替的树节点搜索
    mssql 重新开始标识
    TabContainer实现服务器端回传
    CSS中图片路径的问题
    Javascript在IE下设置innerHTML时出现"未知的运行时错误"
    sql union和union all的用法及效率
    关于动态添加TabPanel遇到的问题以及思考
    关于linq to sql调用存储过程,出现"无法枚举查询结果多次"的问题
    SQL Server 2005连接服务器时的26号错误解决!
    SQL 2000和2005 获取两表的差集
  • 原文地址:https://www.cnblogs.com/shamgod/p/5242479.html
Copyright © 2011-2022 走看看