欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring MVC如何使用@RequestParam注解獲取參數(shù)

 更新時間:2021年10月25日 11:15:04   作者:云淡風(fēng)輕58  
這篇文章主要介紹了Spring MVC實現(xiàn)使用@RequestParam注解獲取參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用@RequestParam注解獲取參數(shù)

創(chuàng)建Hello控制器類

package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
 @RequestMapping("/show")
 public String show(@RequestParam("name")String userName) {
  System.out.println(userName);
  return "index";
 }
}

創(chuàng)建index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>首頁</title>
</head>
<body>
<h3>Spring MVC</h3>
</body>
</html>

啟動Tomcat并訪問

注意:如果參數(shù)被@RequestParam注解,那么默認情況下該參數(shù)不能為空,如果為空則系統(tǒng)會拋出異常。如果希望允許為空,那么要修改它的配置項required為 false。

package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
	@RequestMapping("/show")
	public String show(@RequestParam(value="name",required=false)String userName) {
		System.out.println(userName);
		return "index";
	}
}

啟動 Tomcat再次訪問

@RequestParam無法獲取參數(shù)

application/x-www-form-urlencoded是以表格的形式請求,而application/json則將數(shù)據(jù)序列化后才進行傳遞,如果使用了@RequestParam會在Content里面查找對應(yīng)的數(shù)據(jù)。

結(jié)果因為傳遞的數(shù)據(jù)已經(jīng)被序列化所以不能找到,所以當(dāng)要使用@RequestParam注解時候應(yīng)當(dāng)使用application/x-www-form-urlencoded,而如果想要使用application/json則應(yīng)當(dāng)使用@RequestBody獲取被序列化的參數(shù)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論