화면 구성(resources/templates/auth)

  • register.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>register</title>
</head>
<body>
<form method="post" th:action="@{/auth/save}" th:object="${user}">
  <!--  th:with="Role=${T(com.example.loginpractice.enumerate.Role)}"-->
  <div class="container" style="padding: 15px">
    <div class="insert">
      <input th:field="*{id}" type="hidden"/>
      <div>
        <h2>회원가입 양식</h2>
        <div>
          <div class="col1">이름</div>
          <div class="col2"><input type="text" name="name" maxlength="5" th:field="*{name}"></div>
        </div>
        <div>
          <label class="col1" th:for="*{username}" th:text="|아이디|"><span
              style="color: #ff1034;"> *</span></label>
          <div class="col2">
            <input type="text" name="username" maxlength="10" th:field="*{username}">
            <button type="button" th:onclick="check()" id="checkUsername">중복확인</button>
          </div>
        </div>
        <div>r
          <div class="col1">비밀번호</div>
          <div class="col2">
            <input type="password" th:field="*{password}">
          </div>
        </div>
      </div>
    </div>
    <div class="create" style="padding-top: 10px">
      <button type="button" th:onclick="|location.href='@{/auth/login}'|">가입취소</button>
      <button type=" submit">회원가입</button>
    </div>
  </div>
</form>
<script th:inline="javascript">
  function check() {
    var username = $('#username').val();
    $.ajax({
      url: '/auth/username/check',
      type: 'POST',
      dataType: 'text',
      contentType: 'text/plain; charset=utf-8;',
      data: username,

      success: function (data) {
        if (data == 0) {
          console.log("아이디 없음");
          alert("사용하실 수 있는 아이디입니다.");
        } else {
          console.log("아이디 있음");
          alert("중복된 아이디가 존재합니다.");
        }
      },
      error: function () {
      }
    });
  }
</script>
</body>
</html>

간단하게 아이디, 비밀번호, 사용자 이름 폼을 사용, 아이디 중복확인 기능도 존재

 

  • AuthController
@Controller
@RequiredArgsConstructor
@RequestMapping("/auth")
public class AuthController {

  @NonNull
  private final UserService userService;
  @NonNull
  private final SmartValidator validator;
  
   @RequestMapping("/register")
  public String registerSelect() {
    return "auth/register-select";
  }

  @RequestMapping("/register/{role}")
  public String registerUser(Model model, @PathVariable(name = "role") Role role) {
    User user = new User();
    user.setRole(role);
    model.addAttribute("user", user);
//    model.addAttribute("passwordRuleMessage", PasswordUtil.getPasswordRuleMessage());
    return "auth/register";
  }

  @PostMapping("/save")
  public String save(Model model, @ModelAttribute User user, BindingResult result,
      RedirectAttributes redirectAttr) {

    user.setRole(Role.ROLE_USER);
//    boolean isUser = user.getRole().equals(Role.ROLE_USER) ? true : false;

    validator.validate(user, result, Default.class);

    if (!result.hasErrors()) {
      try {
        userService.save(user);
        redirectAttr.addFlashAttribute("message", "회원가입 성공");
        return "redirect:/auth/login";
      } catch (UserPasswordValidationException e) {
        e.printStackTrace();
      }
    }
//    model.addAttribute("passwordRuleMessage", PasswordUtil.getPasswordRuleMessage());
    return "auth/register";
  }
  
    @ResponseBody
  @GetMapping("/username/check")
  public ResponseEntity<HttpStatus> checkUsername(@RequestParam("username") String username) {
    if (userService.existsByUsername(username)) {
      return ResponseEntity.status(HttpStatus.CONFLICT).build();
    }
    return ResponseEntity.ok().build();
  }

  @ResponseBody
  @GetMapping("/name/check")
  public ResponseEntity<HttpStatus> checkName(@RequestParam("name") String name) {
    if (userService.existsByName(name)) {
      return ResponseEntity.status(HttpStatus.CONFLICT).build();
    }
    return ResponseEntity.ok().build();
  }
  }

사용자를 저장한다.

 

위와 같이 구현하면 사용자 등록에 성공할 수 있다..!

 

❗ 아직 find-account는 구현을 하지 못했다, 다음 포스팅은 권한 부여에 대해 얘기해보려 한다. ❗

+ Recent posts