Spring MVC如何使用@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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Spring/SpringBoot?@RequestParam注解無法讀取application/json格式數(shù)據(jù)問題解決
- 聊聊@RequestParam,@PathParam,@PathVariable等注解的區(qū)別
- SpringMVC注解@RequestParam方法原理解析
- 親測SpringBoot參數(shù)傳遞及@RequestBody注解---踩過的坑及解決
- 解決SpringMVC使用@RequestBody注解報400錯誤的問題
- springMvc注解之@ResponseBody和@RequestBody詳解
- @ResponseBody 和 @RequestBody 注解的區(qū)別
- @RequestParam?和@RequestBody注解的區(qū)別解析
相關(guān)文章
java使用poi讀取ppt文件和poi讀取excel、word示例
這篇文章主要介紹了java使用poi讀取ppt文件和poi讀取excel、word示例,需要的朋友可以參考下2014-03-03Mybatis-plus foreach拼接字符串查詢無數(shù)據(jù)返回問題
這篇文章主要介紹了Mybatis-plus foreach拼接字符串查詢無數(shù)據(jù)返回問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03Java中保留兩位小數(shù)的四種方法實現(xiàn)實例
今天小編就為大家分享一篇關(guān)于Java中保留兩位小數(shù)的四種方法實現(xiàn)實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02Java畢業(yè)設(shè)計實戰(zhàn)之教室預(yù)訂管理系統(tǒng)的實現(xiàn)
這是一個使用了java+SpringBoot+Maven+Vue+mysql開發(fā)的教室預(yù)訂管理系統(tǒng),是一個畢業(yè)設(shè)計的實戰(zhàn)練習(xí),具有教室預(yù)訂管理該有的所有功能,感興趣的朋友快來看看吧2022-02-02解決@Autowired注入空指針問題(利用Bean的生命周期)
這篇文章主要介紹了解決@Autowired注入空指針問題(利用Bean的生命周期),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02