使用 @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";
	}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM