你能夠使用@RequestMapping 註解映射url好比/appointments映射到整個類或者某個特定的處理方法
特別是類級別的註解講一個特定的請求路徑映射到一個 form控制器。使用額外的方法級註解將映射縮小到
一個具體的HTTP方法(GET,POST等等)或者一個HTTP請求參數條件。java
@Controller @RequestMapping("/appointments") public class AppointmentsController { private final AppointmentBook appointmentBook; @Autowired public AppointmentsController(AppointmentBook appointmentBook) { this.appointmentBook = appointmentBook; } @RequestMapping(method = RequestMethod.GET) public Map<String, Appointment> get() { return appointmentBook.getAppointmentsForToday(); } @RequestMapping(path = "/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(path = "/new", method = RequestMethod.GET) public AppointmentForm getNewForm() { return new AppointmentForm(); } @RequestMapping(method = RequestMethod.POST) public String add(@Valid AppointmentForm appointment, BindingResult result) { if (result.hasErrors()) { return "appointments/new"; } appointmentBook.addAppointment(appointment); return "redirect:/appointments"; } }
上面的例子中@RequestMapping被用在不少地方,第一個用法是類級別的,這代表這個控制器的全部處理方法都和 /appointments路徑相關聯。 get()方法對@RequestMapping進一步細化,它僅僅接收GET請求意味着/appointments 路徑下的GET請求使用這個方法。add()方法也是相同的細化,getNewForm()方法將HTTP方法和路徑結合,所以appointments/new路徑下的GET請求使用這個方法。
getForDay()顯示的是@RequestMapping另外一種用法,後面會講解。
類級別的 @RequestMapping並非必須的。若是不使用類級別的@RequestMapping,路徑是絕對路徑,而不是相對路徑。下面的例子展現了一個使用@RequestMapping的multi-action 控制器。app
@Controller public class ClinicController { private final Clinic clinic; @Autowired public ClinicController(Clinic clinic) { this.clinic = clinic; } @RequestMapping("/") public void welcomeHandler() { } @RequestMapping("/vets") public ModelMap vetsHandler() { return new ModelMap(this.clinic.getVets()); } }
上面的例子並無指定GET, PUT, POST等等,由於 @RequestMapping默認匹配全部的HTTP方法。使用@RequestMapping(method=GET)
只是進一步細化。this