使用@RequestParam注解獲取參數
創建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"; } }
創建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并訪問
注意:如果參數被@RequestParam注解,那么默認情況下該參數不能為空,如果為空則系統會拋出異常。如果希望允許為空,那么要修改它的配置項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無法獲取參數
application/x-www-form-urlencoded是以表格的形式請求,而application/json則將數據序列化后才進行傳遞,如果使用了@RequestParam會在Content里面查找對應的數據。
結果因為傳遞的數據已經被序列化所以不能找到,所以當要使用@RequestParam注解時候應當使用application/x-www-form-urlencoded,而如果想要使用application/json則應當使用@RequestBody獲取被序列化的參數
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/dwenxue/article/details/81354692