zoukankan      html  css  js  c++  java
  • 注解@RequestParam——取请求参数

    一、创建index.jsp

    创建一个用来发送请求的测试jsp

    <a href="springMVC/testRequestParam?username=lzj&age=20">Test RequestParam</a>

      当发送该请求时,在控制方法中药获取请求中的参数username和age

    二、控制器方法

     1 @Controller
     2 @RequestMapping("/springMVC")
     3 public class TestSpringMVC {
     4 
     5     /*required:是否必须。默认为 true, 表示请求参数中必须包含对应
     6 的参数,若不存在,将抛出异常*/
     7     @RequestMapping("/testRequestParam")
     8     public String testRequestParam(
     9             @RequestParam(value="username") String username1,
    10             @RequestParam(value="age",required=false) Integer age1){
    11 
    12         System.out.println("testRequestParam: " + "username=" + username1 + "; " + "age=" + age1);
    13         return "success";
    14     }
    15 }

    当点击index.jsp中的请求连接时,控制器会截获该请求并处理请求,@RequestParam注解会把请求中的参数username 和age映射给控制器中的username1和age1参数,执行成功后,回显success.jsp。控制台输出:

    1 testRequestParam: username=lzj; age=20

    注意1:@RequestParam注解中参数age设置了required=false,如果不设置,默认required=true。当required为true时,请求中必须要有age参数,否则会失败;当required为false时,请求中可以没有age参数,请求也不会失败,这种情况可以防止请求中忘记传入某个参数,不至于请求失败。
    注意2:用@RequestParam注解从请求参数中映射到控制器中的参数时,控制器的参数一定要用对象类型或简单类型的包装类。例如

    @RequestParam(value="age") Integer age1)不能写成@RequestParam(value="age") int age1),不能用简单int类型去接收请求中的整数。因为,若请求中的对象为空,则int类型的参数不能接收空对象,int类型的参数必须要有一个默认值的。
    若想用简单类型去接收请求中的值,需要赋值一个默认值,写成如下的形式:@RequestParam(value = "age", required = false, defaultValue = "0") int age1)



  • 相关阅读:
    C#函数式编程
    三种观察者模式的C#实现
    使用C#设计Fluent Interface
    02.Python网络爬虫第二弹《http和https协议》
    03.Python网络爬虫第一弹《Python网络爬虫相关基础概念》
    第七章:Python基础のXML操作和面向对象(一)
    第五章:Python基础の生成器、迭代器、序列化和虚拟环境的应用
    第六章:Python基础の反射与常用模块解密
    第四章:Python基础の快速认识內置函数和操作实战
    第三章:Python基础の函数和文件操作实战
  • 原文地址:https://www.cnblogs.com/huigee/p/9842334.html
Copyright © 2011-2022 走看看