How does Spring MVC use @ RequestParam annotations to get parameters
This article mainly introduces how Spring MVC uses @ RequestParam annotation to get parameters, which is very detailed and has certain reference value. Friends who are interested must read it!
Use the @ RequestParam annotation to get parameters
Create a Hello controller class
Package com.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;@Controllerpublic class Hello {@ RequestMapping ("/ show") public String show (@ RequestParam ("name") String userName) {System.out.println (userName); return "index";}}
Create index.jsp
Home page Spring MVC
Start Tomcat and access
Note: if the parameter is annotated with @ RequestParam, the parameter cannot be empty by default. If it is empty, the system will throw an exception. If you want to allow null, change its configuration item required to false.
Package com.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;@Controllerpublic class Hello {@ RequestMapping ("/ show") public String show (@ RequestParam (value= "name", required=false) String userName) {System.out.println (userName); return "index";}}
Start Tomcat to access again
@ RequestParam cannot get parameters
Application/x-www-form-urlencoded is requested in the form of a table, while application/json serializes the data before passing it. If @ RequestParam is used, it will look up the corresponding data in Content.
The result cannot be found because the passed data has been serialized, so you should use application/x-www-form-urlencoded when you want to use the @ RequestParam annotation, and if you want to use application/json, you should use @ RequestBody to get the serialized parameters
The above is all the content of the article "how Spring MVC uses @ RequestParam annotations to get parameters". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!