@RequestMapping 详解,隔壁都馋哭了
示例:
1、value / method 示例
默认 RequestMapping(“….str…”)即为 value 的值;
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private AppointmentBook appointmentBook;
@Autowired
publ
ic 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";
}
}
value 的 uri 值为以下三类:
A) 可以指定为普通的具体值;
B) 可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);
C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);
example B)
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.POST)
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 示例
cousumes 的样例:
@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}
方法仅处理 request Content-Type 为“application/json”类型的请求。
produces 的样例:
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
方法仅处理 request 请求中 Accept 头中包含了”application/json”的请求,同时暗示了返回的内容类型为 application/json;
3 params、headers 示例
params 的样例:
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
评论