본문 바로가기
스프링과 JPA 기반 웹 어플리케이션 개발/1부 (개발환경, 회원가입, 로그인, 계정설정)

23. 프로필 수정 처리

by Backchus 2020. 4. 21.

정말로 쉬운 폼 처리

  • 비어있는 값을 허용한다. (기존에 있던 값을 삭제하고 싶을 수도 있기 때문에...)
  • 중복된 값을 고민하지 않아도 된다.
  • 확인할 내용은 입력 값의 길이 정도.

폼 처리

  • 에러가 있는 경우 폼 다시 보여주기.
  • 에러가 없는 경우
    • 저장하고,
    • 프로필 수정 페이지 다시 보여주기.(리다이렉트)
    • 수정 완료 메시지.

리다이렉트시에 간단한 데이터를 전달하고 싶다면?

 

RedirectAttributes (Spring Framework 5.2.5.RELEASE API)

A specialization of the Model interface that controllers can use to select attributes for a redirect scenario. Since the intent of adding redirect attributes is very explicit -- i.e. to be used for a redirect URL, attribute values may be formatted as Strin

docs.spring.io

 

SettingsController에 프로필 수정 POST요청을 위한 핸들러 작성

package me.weekbelt.studyolle.settings;
port javax.validation.Valid;

@RequiredArgsConstructor
@Controller
public class SettingsController {

    private final AccountService accountService;

    // 기존 코드 .......

    @PostMapping("/settings/profile")
    public String updateProfile(@CurrentUser Account account,
                                @Valid @ModelAttribute Profile profile,
                                Errors errors, Model model,
                                RedirectAttributes attributes) {
        if (errors.hasErrors()) {
            model.addAttribute(account);
            return "settings/profile";
        }

        accountService.updateProfile(account, profile);
        attributes.addFlashAttribute("message", "프로필을 수정했습니다.");
        return "redirect:" + "/settings/profile";
    }
}

 

AccountService에서 프로필 수정 처리를 위한 updateProfile메소드 작성

package me.weekbelt.studyolle.account;

@Transactional
@RequiredArgsConstructor
@Service
public class AccountService implements UserDetailsService {

    // 기존 코드 .....
    
    public void updateProfile(Account account, Profile profile) {
        account.setUrl(profile.getUrl());
        account.setOccupation(profile.getOccupation());
        account.setLocation(profile.getLocation());
        account.setBio(profile.getBio());
        // TODO: 프로필 이미지 수정
        accountRepository.save(account);
        // TODO: 문제가 하나 더 남아 있습니다.
    }
}

 

 

참고: https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-JPA-%EC%9B%B9%EC%95%B1#

 

스프링과 JPA 기반 웹 애플리케이션 개발 - 인프런

이 강좌에서 여러분은 실제로 운영 중인 서비스를 스프링, JPA 그리고 타임리프를 비롯한 여러 자바 기반의 여러 오픈 소스 기술을 사용하여 웹 애플리케이션을 개발하는 과정을 학습할 수 있습니다. 이 강좌를 충분히 학습한다면 여러분 만의 웹 서비스를 만들거나 취직에 도움이 될만한 포트폴리오를 만들 수 있을 겁니다. 활용 웹 개발 프레임워크 및 라이브러리 Java Spring Spring Boot Spring Data JPA Thymeleaf 온라인 강의 스

www.inflearn.com