zoukankan      html  css  js  c++  java
  • 使用 @RequestParam 将请求参数绑定至方法参数

    你可以使用 @RequestParam 注解将请求参数绑定到你控制器的方法参数上。

    在这之前你需要知道,不加 @RequestParam 注解,直接给方法一个跟 request 中参数名相同的方法参数一样可以获取到 request 中的参数值,而且如果参数值为空的情况下默认为 null 且不会报错:

    @Controller
    public class EditPetForm {
    
    	@GetMapping("/pets")
    	public String setupForm(Integer petId) {
    		System.out.println(petId);
    		return "petForm";
    	}
    
    }
    

    基础用法:

    package com.pudding.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class EditPetForm {
    
    	@GetMapping("/pets")
    	public String setupForm(@RequestParam int petId) {
    		System.out.println(petId);
    		return "petForm";
    	}
    
    }
    

    required 参数

    若参数使用了该注解,则该参数默认是必须提供的,但你也可以把该参数标注为非必须的:只需要将 @RequestParam 注解的 required 属性设置为 false 即可:

    package com.pudding.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class EditPetForm {
    
    	@GetMapping("/pets")
    	public String setupForm(@RequestParam(value = "petId", required = false) Integer petId) {
    		System.out.println(petId);
    		return "petForm";
    	}
    
    }
    

    注意:这里使用的 required = false 是将请求的参数设置为 null ,所以方法里的参数需要为引用类型(Integer),如果使用的是基本类型(int)会出现以下错误:

    java.lang.IllegalStateException: Optional int parameter 'petId' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.
    

    defaultValue 参数

    @RequestParam 还有一个参数 defaulValue 使用它可以指定如果参数为空的情况下的默认参数:

    	@GetMapping("/pets")
    	public String setupForm(@RequestParam(value = "petId", required = false, defaultValue = 0) Integer petId) {
    		System.out.println(petId);
    		return "petForm";
    	}
    
  • 相关阅读:
    O2O创业团队,遇到生死悠关的问题,希望大家支招?
    你所忽视的“办公室政治”
    Mac OS X下给树莓派安装Raspbian系统
    树莓派上的软件安装和卸载命令汇总
    树莓派实现PPPOE拨号上网
    VNC远程登录树莓派的图形界面 -- VNC Server安装与连接
    树莓派玩家必装的几个Android手机APP
    没有鼠标,没有键盘,没有显示器,没有网络,仅通过串口连接控制树莓派
    树莓派2代B型性能极限测试
    朋友分享的设计网站鉴赏 记录
  • 原文地址:https://www.cnblogs.com/lemon-coke-pudding/p/12722950.html
Copyright © 2011-2022 走看看