wwz_ henu 2022-02-13 05:26:14 阅读数:802
origin:https://www.cnblogs.com/xiaoxi/p/5695783.html
1.Controller Method parameter receiving parameter
@RequestMapping("/index1")
public String index1(String name, String age){
return name + age;
}
2. Use HttpServletRequest Receiving parameters
@RequestMapping("/index2")
public String index2(HttpServletRequest request){
String name = request.getParameter("name");
String age = request.getParameter("age");
return name + age;
}
3. Use bean Receiving parameters
Create a corresponding to the request parameter bean
public class UserModel {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Use bean Receiving parameters
@RequestMapping("/index3")
public UserModel index3(UserModel userModel){
String name = userModel.getName();
String age = userModel.getAge();
return userModel;
}
4. Use PathVariable Receiving parameters , Parameters in the receive path
@RequestMapping(value="/index4/{name}/{age}")
public String index4(@PathVariable String name,@PathVariable String age){
return name+age;
}
5. Use RequestParam Receiving parameters , Similar to the first way , If parameters are missing , There will be abnormal
You can use @RequestParam(required = false) Avoid exceptions
Missing parameters will cause exceptions , The lack of name or age All parameters have exceptions
@RequestMapping(value="/index5")
public String index5(@RequestParam String name,@RequestParam String age){
return name+age;
}
The lack of name There will be no exception in the parameter , The lack of age There will be exceptions to the parameter
@RequestMapping(value="/index5")
public String index5(@RequestParam(value = "name",required = false) String name,@RequestParam String age){
return name+age;
}
copyright:author[wwz_ henu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130526124717.html