写点什么

@RequestMapping 详解,隔壁都馋哭了

作者:Java高工P7
  • 2021 年 11 月 09 日
  • 本文字数:1275 字

    阅读完需:约 4 分钟

示例:

1、value / method 示例


默认 RequestMapping(“….str…”)即为 value 的值;


@Controller


@RequestMapping("/appointments")


public class AppointmentsController {


private AppointmentBook appointmentBook;


@Autowired


publ


《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
浏览器打开:qq.cn.hn/FTe 免费领取
复制代码


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 {

用户头像

Java高工P7

关注

还未添加个人签名 2021.11.08 加入

还未添加个人简介

评论

发布
暂无评论
@RequestMapping详解,隔壁都馋哭了