这篇文章对Spring 的MVC @RequestMapping讲解的很清楚,摘记备忘.
@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(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
@RequestMapping(value="/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";
}
}
映射方法是 getNewForm()
/appointments.do
GET请求映射方法是 get()
POST请求映射方法是 add(@Valid AppointmentForm appointment, BindingResult result)
@RequestMapping(value = "/path", params="myParam=myValue") public void add(){...}http://localhost:8080/DynamicWebProject/hao/hello.do?myParam=myValue
URL中只有存在myParam=myValue参数时才被允许访问路径映射的方法
@RequestMapping(value = "/path", method = RequestMethod.POST, headers="content-type=text/*") public void add(){...}只有在URL的头信息中包含有content-type=text/*(content-type=text/xml)的POST请求才能访问add()方法