转自:
http://www.java265.com/JavaFramework/SpringBoot/202206/3779.html
下文笔者讲述SpringBoot请求URL参数的方法分享,如下所示
URL请求参数: 是web客户端同服务器交流数据的一种方式 那么SpringBoot中如何从url中获取指定的参数值呢? 下文将一一道来,如下所示:
方式1:直接将参数写在Controller的形参中
例:
@RequestMapping(\"/addUser1\") public String addUser1(String username,String password) { System.out.println(\"用户名:\"+username); System.out.println(\"密码:\"+password); return \"index\"; } http://localhost:8080/addUser1?username=chengcheng&password=87654321
方式2:使用HttpServletRequest的方式接收
@RequestMapping(\"/addUser2\") public String addUser2(HttpServletRequest request) { String username=request.getParameter(\"username\"); String password=request.getParameter(\"password\"); System.out.println(\"用户名:\"+username); System.out.println(\"密码:\"+password); return \"index\"; }
方式3:使用bean对象接收参数
package demo.model; public class UserModel { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } @RequestMapping(\"/addUser3\") public String addUser3(UserModel user) { System.out.println(\"用户名:\"+user.getUsername()); System.out.println(\"密码:\"+user.getPassword()); return \"index\"; }
方式4:使用@PathVariable获取路径中的参数
@RequestMapping(value=\"/addUser4/{username}/{password}\",method=RequestMethod.GET) public String addUser4(@PathVariable String username,@PathVariable String password) { System.out.println(\"用户名:\"+username); System.out.println(\"密码:\"+password); return \"index\"; } http://localhost:8080/addUser4/usernametest/pwd88888
方式5:使用@ModelAttribute注解获取POST请求的FORM表单数据
Jsp表单: <form action =\"<%=request.getContextPath()%>/demo/addUser5\" method=\"post\"> 用户名: <input type=\"text\" name=\"username\"/><br/> 密 码: <input type=\"password\" name=\"password\"/><br/> <input type=\"submit\" value=\"提交\"/> <input type=\"reset\" value=\"重置\"/> </form> @RequestMapping(value=\"/addUser5\",method=RequestMethod.POST) public String addUser5(@ModelAttribute(\"user\") UserModel user) { System.out.println(\"username is:\"+user.getUsername()); System.out.println(\"password is:\"+user.getPassword()); return \"demo/index\"; }
方式6:使用注解@RequestParam绑定请求参数到方法入参
当请求参数username不存在时会有异常发生 可以通过设置属性required=false解决 例 @RequestParam(value=\"username\", required=false) @RequestMapping(value=\"/addUser6\",method=RequestMethod.GET) public String addUser6(@RequestParam(\"username\") String username,@RequestParam(\"password\") String password) { System.out.println(\"用户名:\"+username); System.out.println(\"密码:\"+password); return \"demo/index\"; }
来源:https://www.cnblogs.com/java265/p/16391840.html
本站部分图文来源于网络,如有侵权请联系删除。