@validated×¢½âʹÓý̳Ì
@validated×¢½âʹÓý̳̳̽ÌÌṩÁËʹÓÃ@validated×¢½â¾ÙÐÐÇëÇó²ÎÊýÑéÖ¤µÄÏêϸ˵Ã÷¡£Ëüº¸ÇÁËʹÓð취¡¢ÑéÖ¤Ô¼Êø£¨ÀýÈç@notnullºÍ@size£©¡¢¹ýʧ´¦Öóͷ£ÒÔ¼°½¨Éè×Ô½ç˵ÑéÖ¤Æ÷¡£Óŵã°üÀ¨¸ÄÉÆ´úÂëÖÊÁ¿¡¢¼ò»¯¹ýʧ´¦Öóͷ£ºÍÌá¸ßÇå¾²ÐÔ¡£
@validated×¢½âʹÓý̳Ì
¼ò½é
@validated×¢½âÊÇÒ»¸öÇ¿Ê¢µÄÑéÖ¤¹¤¾ß£¬ÓÃÓÚÑéÖ¤´«ÈëµÄÇëÇó²ÎÊý£¬È·±£ÆäÖª×ãÌض¨µÄÔ¼ÊøÌõ¼þ¡£
ʹÓ÷½·¨
ҪʹÓÃ@validated×¢½â£¬ÐèÒªÔÚ¿ØÖÆÆ÷ÒªÁìÉÏÌí¼ÓËü£¬ÒªÁìÈçÏ£º
@PostMapping("/create-user") public User createUser(@RequestBody @Validated User user) { // ... }
µÇ¼ºó¸´ÖÆ
ÔÚ@RequestBody×¢½âºóÌí¼Ó@Validated×¢½â£¬ÌåÏÖ¸ÃÒªÁ콫ʹÓÃHibernate Validator¾ÙÐвÎÊýÑéÖ¤¡£
ÑéÖ¤Ô¼Êø
¿ÉÒÔʹÓÃHibernate ValidatorµÄÖÖÖÖ×¢½âÀ´½ç˵ÑéÖ¤Ô¼Êø£¬ÀýÈ磺
- @NotNull: ÑéÖ¤×ֶβ»Îªnull¡£
- @Size: ÑéÖ¤×ֶγ¤¶È¡£
- @Pattern: ÑéÖ¤×Ö¶ÎÊÇ·ñÆ¥ÅäÌض¨ÕýÔò±í´ïʽ¡£
ÀýÈ磺
public class User { @NotNull private String username; @Size(min = 6, max = 20) private String password; }
µÇ¼ºó¸´ÖÆ
¹ýʧ´¦Öóͷ£
ÈôÊÇÑé֤ʧ°Ü£¬Spring Boot½«·µ»ØÒ»¸ö400 Bad RequestÏìÓ¦£¬²¢°üÀ¨ÑéÖ¤¹ýʧµÄÏêϸÐÅÏ¢¡£¹ýʧÏêϸÐÅÏ¢´æ´¢ÔÚBindingResult¹¤¾ßÖУ¬¿ÉÒÔÔÚ¿ØÖÆÆ÷ÒªÁìÖÐͨ¹ý@Valid×¢½â»á¼ûËü£º
public User createUser(@RequestBody @Validated User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { // ´¦Öóͷ£ÑéÖ¤¹ýʧ } // ... }
µÇ¼ºó¸´ÖÆ
×Ô½ç˵ÑéÖ¤Æ÷
ÈôÊÇÐèÒª×Ô½ç˵ÑéÖ¤Âß¼£¬¿ÉÒÔʹÓÃ@Validator×¢½â½¨Éè×Ô½ç˵ÑéÖ¤Æ÷£¬²¢½«Æä×¢²áµ½Spring BootÖС£
Óŵã
ʹÓÃ@validated×¢½âµÄÀûÒæ°üÀ¨£º
- ¸ÄÉÆ´úÂëÖÊÁ¿£ºÍ¨¹ýÑéÖ¤ÊäÈ룬ïÔÌÁËÔËÐÐʱ¹ýʧ¡£
- ¼ò»¯¹ýʧ´¦Öóͷ££ºSpring Boot×Ô¶¯´¦Öóͷ£ÑéÖ¤¹ýʧ²¢ÌṩÏêϸ¹ýʧÐÂÎÅ¡£
- Ìá¸ßÇå¾²ÐÔ£º±ÜÃⲻ׼ȷµÄ»ò¶ñÒâÊý¾Ýͨ¹ýÑéÖ¤£¬Ìá¸ßÓ¦ÓóÌÐòµÄÇå¾²ÐÔ¡£
ÒÔÉϾÍÊÇ@validated×¢½âʹÓý̵̳ÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡