Skip to content

Spring MVC

luoml edited this page Jul 16, 2017 · 6 revisions

1. @RequestMapping

  • value 处理方法的请求URL

  • method 处理方法的Http Method类型,如:RequestMethod.GET

  • params 请求URL中必须包含(或不包含)的某些参数

    • params="var" 请求URL中必须包含var参数,如:/find?var=test
    • params="!var" 请求URL中不能包含var参数
    • params="var=test" 请求URL中必须包含var=test,如:/find?var=test
    • params="var!=test" 请求URL中不能包含var=test
  • @RequestMapping支持Ant风格的通配符

    • ? 匹配任意一个字符
    • * 匹配任意多个字符
    • ** 匹配多层路径

2. 请求参数获取方法

2.1. @PathVariable

@RequestMapping("/user/{id}", method = RequestMethod.GET)
public User get(@PathVariable("id") Integer id) { ... }

2.2. @RequestParam (method?param=value&paramX=valueX)

// 可以通过 required 设置参数是否必填
@RequestMapping("/user", method = RequestMethod.GET)
public User get(@RequestParam("id") Integer id) { ... }

2.3. @ModelAttribute (获取POST请求的Form表单数据)

// jsp
<form method="post" action="*.do">
  UserName: <input id="username" type="text" name="username"/>
  Password: <input id="password" type="password" name="password"/>
  <input type="submit" value="Submit" />
</form>

// po
public class User {
  private String username;
  private String password;
  
  ......
}

// Controller
@RequestMapping(method = RequestMethod.POST) 
public void login(@ModelAttribute("user") User user) { ... }

2.4. HttpServletRequest

@RequestMapping("/user", method = RequestMethod.GET)
public User get(HttpServletRequest request) { ... }

Clone this wiki locally