최원종의 개발 블로그

V3-10 회원정보보기 및 수정 및세션 동기화 처리 본문

Spring boot 입문

V3-10 회원정보보기 및 수정 및세션 동기화 처리

chl6698 2026. 5. 15. 16:40

회원정보수정화면


application-dev.yml 설정 파일 수정

  # SQL 초기화 설정
  sql:
    init:
      mode: always  # 외부 DB(MySQL)에서도 실행되도록 설정
      #mode: never # 절대 실행 안됨
      data-locations:
        - classpath:db/data.sql

spring.sql.init.mode 옵션 (SQL 스크립트 실행 제어)

직접 작성한 data.sql이나 schema.sql 파일을 어느 환경에서 실행할지 결정

always : 모든 데이터베이스에 대해 항상 SQL 스크립트를 실행함 (MySQL 등 외부 DB 사용 시 필수)
embedded : H2, HSQL, Derby 등 내장형(In-Memory) DB일 때만 실행함 (기본값)
never : SQL 스크립트 초기화 기능을 사용하지 않음

 

hibernate.ddl-auto

spring.jpa.hibernate.ddl-auto 설정에서 사용하는 값. 이건 SQL 파일을 실행하는 게 아니라,
JPA(Hibernate)가 Entity 클래스를 보고 자동으로 테이블을 만들어주는 기능

옵션:설명
create : 기존 테이블을 삭제하고 새로 생성
create-drop : 시작할 때 생성하고, 종료할 때 삭제 (테스트용)
update : 변경된 부분만 반영 (기존 데이터 유지)
validate : Entity와 DB 테이블이 잘 맞는지 검사만 함
none : 아무것도 하지 않음 (운영 환경 권장)

회원 정보 수정 화면 코드

user/update-form.mustahce 파일 (회원수정화면)

{{> layout/header}}
<div class="container p-5 flex-grow-1">
    <div class="card">
        <div class="card-header"><b>회원수정을해주세요</b></div>
        <div class="card-body">
            <form action="/user/update" method="post">
                <div class="mb-3">
                    <input type="text" class="form-control" name="username" value="" disabled>
                </div>
                <div class="mb-3">
                    <input type="text" class="form-control" name="password" value="" >
                </div>
                <div class="mb-3">
                    <input type="text" class="form-control" name="email" value="" disabled>
                </div>
                <button class="btn btn-primary form-control">회원정보수정</button>
            </form>
        </div>
    </div>
</div>
{{> layout/footer}}

 


UserController 코드

 

    // 프로필 수정 기능 요청
    @PostMapping("/user/update")
    public String updateProc(UserRequest.UpdateDTO updateDTO, HttpSession session) {

        User sessionUser = (User) session.getAttribute("sessionUser");
        if (sessionUser == null) {
            return "redirect:/login-form";
        }
        try {
            updateDTO.validate();
            // 더티 체킹 전략
            User userEntity = userRepository.updateById(sessionUser.getId(), updateDTO);
            // 세션 동기화 처리
            session.setAttribute("sessionUser", userEntity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "redirect:/";
    }

 

 


UserRepository 코드

 

    public User findById(Integer id) {
       User user = em.find(User.class, id);
       if(user == null) {
           throw new RuntimeException("사용자를 찾을 수 없습니다");
       }
       return user;
    }

회원 정보 수정 기능 요청

UserResponse(UpdateDTO)코드

    public static class UpdateDTO {

        private String password;

        public void validate() {
            if(password == null || password.isBlank()) {
                throw new IllegalArgumentException("비밀번호는 필수 입니다");
            }
            if (password.length() < 4) {
                throw new IllegalArgumentException("비밀번호는 4자 이상이어야 합니다");
            }
        }
    }

 

 

UserController 코드

// 회원정보수정 기능 요청
@PostMapping("/user/update")
public String updateProc(UserRequest.UpdateDTO updateDTO, HttpSession session) {

    User sessionUser = (User)session.getAttribute("sessionUser");
    if(sessionUser == null) {
        return "redirect:/login-form";
    }
    try {
        updateDTO.validate();
        // 더티 체킹 전략
        userRepository.updateById(sessionUser.getId(), updateDTO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return "redirect:/";
}

    @Transactional
    public User updateById(Integer id, UserRequest.UpdateDTO updateDTO) {
        User userEntity = findById(id); // 영속성 컨텍스트에 관리되는 엔티티
        userEntity.setPassword(updateDTO.getPassword()); // 객체의 상태값 변경 함. - password
        return userEntity;
    }