@RequestMapping注解可以将HTTP请求映射给controller
来处理,包括返回视图页面的controller和Rest服务的controller。
1、@RequestMapping可以添加到类或者方法上。
@Controller
@RequestMapping(value = "/", method = RequestMethod.GET)
public class ContactController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String redirectToContactPage() {
return "redirect:contact";
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String toAdminPage() {
return "admin";
}
在上面的例子中,@RequestMapping加在了类和方法上:
访问/的请求会被ContactController的redirectToContactPage()方法处理
访问/admin的请求会被ContactController的toAdminPage()方法处理
2、@RequestMapping映射多个URL
@Controller
@RequestMapping("/")
public class ContactController {
@RequestMapping(value={"", "/page", "page*","view/*"})
String multipleMapping(){
return "Hello";
}
}
访问下列地址都会被ContactController的multipleMapping方法处理:
· localhost:8080/
· localhost:8080/page
· localhost:8080/pagehello
· localhost:8080/view/
· localhost:8080/view/view1
3、@RequestParam请求参数
使用@RequestParam可以将HTTP请求参数绑定到controller中方法的参数上,例如
@Controller
@RequestMapping("/")
public class ContactController {
@RequestMapping(value=/hello)
String sayHelloToUser(@RequestParam("username") String username){
return "Hello " + username;
}
@RequestMapping(value=/hi)
String sayHiToUser(@RequestParam String username){
return "Hello " + username;
}
}
·当访问localhost:8080/hello?username=ted时,值ted会绑定到参数username上,结果是Hello ted。
·当HTTP请求参数和controller方法的参数名称相同时,可以省略,如sayHiToUser方法
·@RequestParam默认要求参数是必要的,通过设置@RequestParam(value = “username”, required = false)设为可选,这样HTTP请求不带username参数也是可以访问到指定的方法。
·当HTTP请求不带username参数时,还可以设置它的默认值,如@RequestParam(value = “username”, defaultValue = “mattie”)
4、指定HTTP请求类型
HTTP请求有GET, POST, PUT, DELETE等,@RequestMapping可以处理特定的请求类型。相当于如下注解:
·GetMapping
·PostMapping
·PutMapping
·DeleteMapping
@Controller
@RequestMapping("/")
public class ContactController {
@RequestMapping(value=/hello, method = RequestMethod.GET)
String sayHelloToUser(@RequestParam("username") String username){
return "Hello " + username;
}
@PostMapping(value=/hello)
String login(@RequestParam("password") String password){
return "Login Success!";
}
}
上面的例子中login方法处理POST类型的请求。
5、@RequestMapping处理动态URL
和注解@PathVariable联合使用,可以解析HTTP请求中的动态URL。
@Controller
@RequestMapping("/")
public class ContactController {
@RequestMapping(value = "/contacts/{contactname}", method = RequestMethod.GET)
String getContactName(@PathVariable("contactname") String name){
return "Contact name is " + name;
}
}
上面的例子中,访问localhost:8080/contacts/ted和localhost:8080/contacts/mattie都会被ContactController的getContactName方法处理,结果分别是Contact name is ted和Contact name is mattie。
动态URL也可以使用正则来匹配:
上面的例子中,访问localhost:8080/wears/shoes和localhost:8080/foods/bread都会被ShopController的getProductName方法处理
但是访问localhost:8080/101/fun不会被处理。
注意@RequestParam和@PathVariable的区别:@RequestParam解析URL中特定的请求参数的值;而@PathVariable用来匹配URL路径的规则和模式。