docs/Spring全家桶/SpringMVC/SpringMVC常见注解.md
ڱ̳Уǽ̽ org.springframework.web.bind.annotation е Spring Web ע͡
˵@RequestMapping @Controller ڲ ʹã
·ƺֵӳ䵽ĸ URL ݵ HTTP params HTTP Ĵڡڻֵ headers HTTP ͷĴڡڻֵ ģ÷ HTTP Щý produces÷ HTTP ӦЩý һʾ
@Controller
class VehicleController {
@RequestMapping(value = "/vehicles/home", method = RequestMethod.GET)
String home() {
return "home";
}
}
༶ӦôעͣǿΪ @Controller едṩĬá Ψһ Spring ʹ÷øǵḽ·ֵ URL
磬úЧһģ
@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
class VehicleController {
@RequestMapping("/home")
String home() {
return "home";
}
}
⣬@GetMapping@PostMapping@PutMapping@DeleteMapping @PatchMapping @RequestMapping IJͬ壬HTTP ѷֱΪGETPOSTPUTDELETE PATCH
Щ Spring 4.3 汾ʼá
Ǽ@RequestBody HTTP ӳ䵽һ
@PostMapping("/save")
void saveVehicle(@RequestBody Vehicle vehicle) {
// ...
}
лԶģȡ͡
˵˵@PathVariable
עָʾ URI ģ ǿʹ @RequestMapping עָ URI ģ壬ʹ @PathVariable ģ岿֮һ
ǿʹƻֵʵһ㣺
@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable("id") long id) {
// ...
}
ģвֵ뷽ƥ䣬ǾͲעָ
@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable long id) {
// ...
}
⣬ǿͨIJΪ false ·Ϊѡ
@RequestMapping("/{id}")
Vehicle getVehicle(@PathVariable(required = false) long id) {
// ...
}
We use @RequestParam for accessing HTTP request parameters:
@RequestMapping
Vehicle getVehicleByParam(@RequestParam("id") long id) {
// ...
}
@PathVariable עͬѡ
Щ֮⣬ Spring зûֵΪֵʱǿʹ @RequestParam ָעֵ ΪˣDZ defaultValue
ṩĬֵʽ required Ϊ false
@RequestMapping("/buy")
Car buyCar(@RequestParam(defaultValue = "5") int seatCount) {
// ...
}
˲֮⣬ǻԷ HTTP ֣cookie ͱͷ
ǿԷֱʹע@CookieValue @RequestHeader ǡ
ڽIJУǽ Spring MVC в HTTP Ӧע͡
@ResponseBody Spring ὫĽΪӦ
@ResponseBody
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}
עע @Controller ࣬ʹ
ʹôעͣǿһԶ ׳κָ쳣ʱSpring ô˷
쳣Ϊݸ
@ExceptionHandler(IllegalArgumentException.class)
void onIllegalArgumentException(IllegalArgumentException exception) {
// ...
}
ʹôעͶעָͣӦ HTTP ״̬ ǿʹ code value ״̬롣
⣬ǿʹ reason ṩԭ
ҲԽ@ExceptionHandler һʹã
@ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) void onIllegalArgumentException(IllegalArgumentException exception) { // ... }
й HTTP Ӧ״̬ĸϢʱġ
һЩעͲֱӹ HTTP Ӧ ڽIJУǽġ
ǿʹ@Controller һSpring MVC йظϢǹ Spring Bean Annotations ¡
@RestController @Controller @ResponseBody
ˣǵЧģ
@Controller
@ResponseBody
class VehicleRestController {
// ...
}
@RestController
class VehicleRestController {
// ...
}
ͨע⣬ǿͨṩģͼѾ MVC @Controller ģеԪأ
@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicleInModel) {
// ...
}
@PathVariable @RequestParam һͬƣDzָģͼ
@PostMapping("/assemble")
void assembleVehicle(@ModelAttribute Vehicle vehicle) {
// ...
}
⣬@ModelAttributeһ;עһSpringԶķֵӵģУ
@ModelAttribute("vehicle")
Vehicle getVehicle() {
// ...
}
ǰһDzָģͼSpring Ĭʹ÷ƣ
@ModelAttribute
Vehicle vehicle() {
// ...
}
Spring ֮ǰ @ModelAttribute ע͵ķ
й @ModelAttribute ĸϢıġ
@CrossOrigin Ϊע͵ÿͨţ
@CrossOrigin
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}
һ࣬е
ǿʹôע͵IJ CORS Ϊ
йϸϢʱġ