@RequestMapping 用法详解之地址映射
@RequestMapping 用法详解之地址映射
简介:
1、 value, method;
2、 consumes,produces;
3、 params,headers;
示例:
1、value / method 示例
- @Controller
- @RequestMapping("/appointments")
- public class AppointmentsController {
- private 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";
- }
- }
- @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
- public String findOwner(@PathVariable String ownerId, Model model) {
- Owner owner = ownerService.findOwner(ownerId);
- model.addAttribute("owner", owner);
- return "displayOwner";
- }
example C)
- @RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
- public void handle(@PathVariable String version, @PathVariable String extension) {
- // ...
- }
- }
2 consumes、produces 示例
- @Controller
- @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
- public void addPet(@RequestBody Pet pet, Model model) {
- // implementation omitted
- }
- @Controller
- @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
- @ResponseBody
- public Pet getPet(@PathVariable String petId, Model model) {
- // implementation omitted
- }
3 params、headers 示例
- @Controller
- @RequestMapping("/owners/{ownerId}")
- public class RelativePathUriTemplateController {
- @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
- public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
- // implementation omitted
- }
- }
- @Controller
- @RequestMapping("/owners/{ownerId}")
- public class RelativePathUriTemplateController {
- @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
- public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
- // implementation omitted
- }
- }