你可以使用@RequestMapping 注解映射url比如/appointments映射到整个类或者某个特定的处理方法
特别是类级别的注解讲一个特定的请求路径映射到一个 form控制器。使用额外的方法级注解将映射缩小到
一个具体的HTTP方法(GET,POST等等)或者一个HTTP请求参数条件。
@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 控制器。
@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)
只是进一步细化。