🌏 WEB/JAVA

화면에 μ›ν•˜λŠ” μ—λŸ¬λ©”μ‹œμ§€ 보내기

μ• μ •μ“° 2023. 3. 9. 10:47

κ°„λ‹¨ν•œ κΈ°λ³Έ 등둝 νŽ˜μ΄μ§€λΌμ„œ λ‹€λ₯Έμ½”λ“œμ™€ λ˜‘κ°™μ΄ ν•˜λ‹€κ°€ μ•½κ°„ λ³€ν™”λ₯Ό μ£Όμ—ˆλ‹€.

html μ—μ„œ ajax둜 μ„œλ²„μ—κ²Œ μš”μ²­ν• λ•Œ success 즉 톡신에 μ„±κ³΅ν•˜κ³  java μ—μ„œ return 으둜 ok (boolean) 을 λ‚΄λ €μ£Όλ©΄ message λ₯Ό 띄어쀀닀. 

    const updateDriver = function () {

      if (confirm("λ“±λ‘ν•˜μ‹œκ² μŠ΅λ‹ˆκΉŒ?")) {
        $.ajax({
          type: "POST",
          url: "/create",
          data: $("#createForm").serialize(),
          dataType: 'json',
          success: function (r) {
            alert(r.message);
            if (r.OK) {
              location.href = '/list';
            }
          },
          error: function (xhr, status, error) {
            alert(error);
          }
        });
      }
    }

 

try-catch λ₯Ό μ μš©ν•΄λ³΄μ•˜λ‹€  User.createUser(dto) μ—μ„œ Assert.hasText() λ₯Ό 톡해 μœ νš¨μ„±μ΄ κ²€μ¦λ˜μ§€ μ•ŠμœΌλ©΄ μ˜ˆμ™Έλ₯Ό λ˜μ§„λ‹€. μ–΄λ–€ μ˜ˆμ™ΈμΈμ§€ ν™•μΈν•˜λ €λ©΄ ν•΄λ‹Ή 클래슀둜 μ΄λ™ν•˜μ—¬ ν™•μΈν•œλ‹€.

IllegalArgumentException 을 catch ν•˜λ©΄ 될것같닀

 

  @Transactional
  @Override
  public ServiceResult create(Dto dto) {
    ServiceResult serviceResult = ServiceResult.builder().OK(false).build();
    try {
      repository.save(User.createUser(dto));
    } catch (IllegalArgumentException e) {
      serviceResult.setMessage(e.getMessage());
      return serviceResult;
    }
    serviceResult.setMessage("μ‚¬μš©μž 등둝이 μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.");
    serviceResult.setOK(true);
    return serviceResult;
  }

 

public static User createUser(Dto dto) {
    Assert.hasText(dto.getName(), "μ‚¬μš©μž 이름은 ν•„μˆ˜ μž…λ‹ˆλ‹€.");
    Assert.hasText(dto.getCellphone(), "μ‚¬μš©μž νœ΄λŒ€ν° λ²ˆν˜ΈλŠ” ν•„μˆ˜ μž…λ‹ˆλ‹€.");
    return User.builder()
        .name(dto.getName()).cellPhone(dto.getCellphone()).build());
  }

 

μ΄λ ‡κ²Œ ν•˜λ©΄ ν™”λ©΄μ—μ„œ μœ νš¨μ„± 검사 + μ„œλ²„μ—μ„œλ„ μœ νš¨μ„± 검사λ₯Ό ν•΄μ„œ 슀크립트 였λ₯˜κ°€ λ‚˜λ”λΌλ„ μ›ν•˜λŠ” μ—λŸ¬λ©”μ‹œμ§€λ₯Ό λ°˜ν™˜ν•  수 μžˆλ‹€.

λ°˜μ‘ν˜•