亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

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>首頁(yè)</title>
</head>
<body>
<h3>Spring MVC</h3>
</body>
</html>

啟動(dòng)Tomcat并訪問(wèn)

注意:如果參數(shù)被@RequestParam注解,那么默認(rèn)情況下該參數(shù)不能為空,如果為空則系統(tǒng)會(huì)拋出異常。如果希望允許為空,那么要修改它的配置項(xià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";
	}
}

啟動(dòng) Tomcat再次訪問(wèn)

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

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

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

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

相關(guān)文章

最新評(píng)論