Spring MVC初步使用

Spring MVC 几种传参方式

本次沿用上次的工程,在controller中添加几个方法

创建User模型

public class User {

  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;
  }

}

修改IndexController

  • 直接把表单参数写入Controller的相应方法中
 @RequestMapping("/addUser1")
  public String addUser1(String username, String password) {
    System.out.println("username is:" + username);
    System.out.println("password is:" + password);
    return "index";
  }
  • 通过user bean 来接收
  @RequestMapping("/addUser2")
  public String addUser3(UserModel user) {
    System.out.println("username is:"+user.getUsername());
    System.out.println("password is:"+user.getPassword());
    return "index";
  }
  • 通过HttpServletRequest来接收
@RequestMapping("/addUser3")
  public String addUser2(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";
  }
  • 通过PathVariable接收
  @RequestMapping(value = "/addUser4/{username}/{password}", method = RequestMethod.GET)
  public String addUser4(@PathVariable String username, @PathVariable String password) {
    System.out.println("username is:" + username);
    System.out.println("password is:" + password);
    return "index";
  }
  • 用注解@RequestParam绑定请求参数
  @RequestMapping(value = "/addUser5", method = RequestMethod.GET)
  public String addUser6(@RequestParam("username") String username, @RequestParam("password") String password) {
    System.out.println("username is:" + username);
    System.out.println("password is:" + password);
    return "index";
  }

测试接口

测试使用的是火狐的HttpRequest插件,使用类似的工具也可以,或者写一个HTML表单,这里不在多解释

clipboard.png
可以看到请求成功,并成功跳转到首页

clipboard.png

服务器输出了请求


zorpan
41 声望14 粉丝

记笔记