在 Spring MVC 应用程序中,RequestDispatcher (在 Front Controller 之下) 这个 servlet 负责将进入的 HTTP 请求路由到控制器的处理方法。
在对 Spring MVC 进行的配置的时候, 你需要指定请求与处理方法之间的映射关系。
要配置 Web 请求的映射,就需要你用上 @RequestMapping 注解。(注意在类上可以不用配置RequestMapping,但是方法上一定要配置(RequestMapping))
1、实例
@Controller
@RequestMapping("/home") public class IndexController { @RequestMapping("/") String get() { //mapped to hostname:/home/ return "Hello from get"; } @RequestMapping("/index") String index() { //mapped to hostname:/home/index return "Hello from index"; } }
2、对与RequestMapping和RequestParam配合使用可以将请求的参数同处理方法的参数绑定在一起
@Controller @RequestMapping("/home") public class IndexController { @RequestMapping(value = "/id") String getIdByValue(@RequestParam("id") String personId) { System.out.println("ID is " + personId); return "Get ID from query string of URL with value element"; } @RequestMapping(value = "/personId") String getId(@RequestParam String personId) { System.out.println("ID is " + personId); return "Get ID from query string of URL without value element"; } }
如果请求参数和处理方法参数的名称一样的话,@RequestParam 注解的 value 这个参数就可省掉了
3、Spring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH,所有的请求默认都会是 HTTP GET 类型的
@Controller @RequestMapping("/home") public class IndexController { @RequestMapping(method = RequestMethod.GET) String get() { return "Hello from get"; } @RequestMapping(method = RequestMethod.DELETE) String delete() { return "Hello from delete"; } @RequestMapping(method = RequestMethod.POST) String post() { return "Hello from post"; } @RequestMapping(method = RequestMethod.PUT) String put() { return "Hello from put"; } @RequestMapping(method = RequestMethod.PATCH) String patch() { return "Hello from patch"; } }