1将请求映射到方法上
//get方式的rest风格请求,路径带有参数
@RequestMapping("/accounts/{username}")
//使用正则表达式
@RequestMapping("/accounts/{username:.*}"
//根据foo参数的有无匹配请求
@RequestMapping(parameters="foo")
@RequestMapping(parameters="!foo")
//根据参数的值匹配请求
@RequestMapping(parameters="foo=123")
//通过判断有无头信息匹配请求
@RequestMapping(headers="Foo-Header")
@RequestMapping(headers="!Foo-Header")
//根据头信息的值判断
@RequestMapping(headers="content-type=text/*")
2处理请求数据
//获取查询字符串参数,cookie,httpheader数据
@RequestMapping(method=GET)
public void foo(@RequestParam("q") String q, @CookieValue("c") String c, @RequestHeader("h") String h) {
}
//如果变量名和参数名一样,可以省略
public void foo(@RequestParam String q, @CookieValue c, @RequestHeader h) {
}
public void foo(String q,String q2) {
}
post方法获取参数
@RequestMapping(method=POST)
public void foo(@RequestParam String name, @RequestParam creditCardNumber, @RequestParam expirationDate) {
}
//使用实体类匹配参数,name与属性名要一致
@RequestMapping(method=POST)
public void foo(CreditCard creditCard) {
// POST /creditcard/1
// name=Bond
// creditCardNumber=1234123412341234
// expiration=12-12-2012
}
//如果是Json字符串,并且和实体类对应key和属性名一样
@RequestMapping(method=POST)
public void createAccount(@RequestBody Account account) {
// Spring MVC
}
3响应请求
@RequestMapping(value="/{username}", method=GET)
@ResponseBody
public Account getAccount(@PathVariable String username) {
return accountRepository.findAccountByUsername(username);
}
4异常处理
@Controller
@RequestMapping("/accounts")
public class AccountController {
@ResponseStatus(NOT_FOUND)
@ExceptionHandler({NoResultException.class})
public void handle() {
// ...
}
}
如果在handle中抛出了异常NoResultException,那么就会捕获到并且处理然后返回一个404错误。