尊龙凯时人生就是搏

@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×¢½âʹÓý̵̳ÄÏêϸÄÚÈÝ £¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí £¬°æȨÕùÒéÓë±¾Õ¾ÎÞ¹Ø £¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í尊龙凯时人生就是搏ÂËÓÍ»úÍø¹Ù·½Ì¬¶È £¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ £¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢ £¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢ £¬ÇëÄúÁ¬Ã¦ÁªÏµ尊龙凯时人生就是搏ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ尊龙凯时人生就是搏

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎå £¬9:30-18:30 £¬½ÚãåÈÕÐÝÏ¢

QR code
sitemap¡¢ÍøÕ¾µØͼ