SpringMVC 学习之 @RequestMapping 注解
@RequestMapping
是一个用来处理请求映射的注解,它可以用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示该方法响应的是以此注解的值为路径的请求。
解决方案1:
@Controller
@RequestMapping("/appointments")
public class AppointmentController {
@RequestMapping(method = RequestMethod.GET)
public String getAppointments() {
// ... 处理获取预约的逻辑
return "appointments";
}
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String newAppointment() {
// ... 处理创建新预约的逻辑
return "appointment_new";
}
@RequestMapping(method = RequestMethod.POST)
public String createAppointment() {
// ... 处理创建新预约的逻辑
return "redirect:/appointments";
}
}
在这个例子中,@Controller
和 @RequestMapping("/appointments")
组合在一个类上,这意味着所有的请求映射都以 "/appointments" 作为父路径。
解决方案2:
@Controller
public class AppointmentController {
@RequestMapping("/appointments")
public String getAppointments() {
// ... 处理获取预约的逻辑
return "appointments";
}
@RequestMapping("/appointments/new")
public String newAppointment() {
// ... 处理创建新预约的逻辑
return "appointment_new";
}
@RequestMapping(value = "/appointments", method = RequestMethod.POST)
public String createAppointment() {
// ... 处理创建新预约的逻辑
return "redirect:/appointments";
}
}
在这个例子中,每个方法的 @RequestMapping
都是独立的,每个方法的路径都是绝对路径,不以任何类级别的注解为前缀。
解决方案3:
@Controller
public class AppointmentController {
@RequestMapping(value = "/appointments", method = RequestMethod.GET)
public String getAppointments() {
// ... 处理获取预约的逻辑
return "appointments";
}
@RequestMapping(value = "/appointments/new", method = RequestMethod.GET)
public String newAppointment() {
// ... 处理创建新预约的逻辑
return "appointment_new";
}
@RequestMapping(value = "/appointments", method = RequestMethod.POST)
public String createAppointment() {
// ... 处理创建新预约的逻辑
return "redirect:/appointments";
}
}
在这个例子中,每个方法的 @RequestMapping
都指定了请求的方法,这样做可以确保请求的方法与注解中指定的方法一致,否则会抛出异常。
解决方案4:
@Controller
public class AppointmentController {
@RequestMapping(value = "/appointments", method = RequestMethod.GET)
public String getAppointments(Model model) {
List<Appointment> appointments = appointmentService.findAll();
model.addAttribute("ap
评论已关闭