本文整理了六种获取请求参数的方式:表单、HttpServletRequest 、bean 接受、@PathVariable 、@ModelAttribute、@RequestParam;并简单分析了其相应的使用场景及适用请求方式。
- 直接把表单的参数写在 Controller 相应的方法的形参中,适用于 get 方式提交,不适用于 post 方式提交:
- /**
- * 通过 Controller 的形参接受数据
- * @param username
- * @param password
- * @return
- */
- @RequestMapping("/addUser")
- public String addUser(String username,String password) {
- System.out.println("username is:"+username);
- System.out.println("password is:"+password);
- return "index";
- }
- 通过 HttpServletRequest 接收,post 方式和 get 方式都可以:
- /**
- * 通过 HttpServletRequest 接收
- * @param request
- * @return
- */
- @RequestMapping("/addUser")
- public String addUser(HttpServletRequest request) {
- String username=request.getParameter("username");
- String password=request.getParameter("password");
- System.out.println("username is:"+username);
- System.out.println("password is:"+password);
- return "index";
- }
- 通过一个 bean 来接收,post 方式和 get 方式都可以:
- /**
- * 通过一个 bean(实体类)来接收
- * @param user
- * @return
- */
- @RequestMapping("/addUser")
- public String addUser(UserModel user) {
- System.out.println("username is:"+user.getUsername());
- System.out.println("password is:"+user.getPassword());
- return "index";
- }
- 通过@PathVariable 获取路径中的参数(详见:@RequestParam 和@PathVariable 区别):
- /**
- * 通过@PathVariable 获取路径中的参数
- * @param username
- * @param password
- * @return
- */
- @RequestMapping(value="/addUser/{username}/{password}",method=RequestMethod.GET)
- public String addUser(@PathVariable String username, @PathVariable String password) {
- System.out.println("username is:"+username);
- System.out.println("password is:"+password);
- return "index";
- }
- 使用@ModelAttribute 注解获取POST 请求的表单数据:
- <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>
Java Controller 如下:
- /**
- * 使用@ModelAttribute 注解获取 POST 请求的 FORM 表单数据
- * @param user
- * @return
- */
- @RequestMapping(value="/addUser",method=RequestMethod.POST)
- public String addUser(@ModelAttribute("user") UserModel user) {
- System.out.println("username is:"+user.getUsername());
- System.out.println("password is:"+user.getPassword());
- return "index";
- }
- 用注解@RequestParam 绑定请求参数到方法入参:
- /**
- * 用注解@RequestParam 绑定请求参数到方法入参
- * @param username
- * @param password
- * @return
- */
- @RequestMapping(value="/addUser",method=RequestMethod.GET)
- public String addUser(@RequestParam("username") String username,@RequestParam("password") String password) {
- System.out.println("username is:"+username);
- System.out.println("password is:"+password);
- return "index";
- }