안녕하세요. 이어서 Retrofit2를 이용한 안드로이드와 스프링 서버 통신 스프링에 대하여 작성해보겠습니다.
이전 게시물인 1편을 읽고 이번 게시물을 읽으시는 것을 추천드립니다.
아래에 링크 달아드리겠습니다.
https://pinlib.tistory.com/entry/retrofit2-1
Retrofit2를 이용한 안드로이드와 스프링 서버 통신(안드로이드편)(안드로이드 서버통신)
안녕하세요. 오늘은 Retrofit2를 이용한 안드로이드와 스프링 서버 통신에 대하여 작성해보겠습니다. 1. Retrofit2란Retrofit2는 Android 및 Java 애플리케이션에서 HTTP 네트워크 통신을 쉽게
pinlib.tistory.com
2. Spring과 Database 연결하기
1) application properties
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/secret_diary
spring.datasource.username=root
spring.datasource.password= 비밀번호
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
DB와의 연결을 위해 DB정보를 spring의 application properties에 작성합니다.
3. CRUD 구현
CRUD의 경우 1편인 android에서 작성한 method와 짝을 이루게 작성하였습니다.
1편의 내용을 반드시 참조하시길 바랍니다.
1) Create
@PostMapping("security/join")
public String signup(@Validated @RequestBody JoinRequestDTO joinRequestDTO){
userService.joinUser(joinRequestDTO);
return "success";
}
안드로이드에서는 userModel에 data를 감싸서 전달했다면 spring에서는 JoinRequestDTO에 데이터를 감싸서 데이터를 받아와 사용합니다.
@Validated는 Spring Framework에서 데이터 유효성 검증(Validation)을 수행할 때 사용하는 어노테이션입니다.
이 어노테이션은 컨트롤러나 서비스 계층에서 메서드의 파라미터나 객체에 대해 유효성 검사를 수행할 수 있도록 도와줍니다.
주로 @NotNull, @Size, @Min, @Max와 같은 유효성 검증 어노테이션을 함께 사용하여 파라미터의 값이 적절한지 검사합니다.
@RequestBody의 경우 Spring MVC에서 HTTP 요청의 본문(Body)을 메서드의 파라미터로 매핑할 때 사용하는 어노테이션입니다. 주로 JSON, XML, 혹은 다른 형식의 데이터를 객체로 변환하여 전달받을 때 사용합니다.
안드로이드에서 @Body를 통해 data를 보냈으므로 spring에서 @RequestBody를 통해 data를 받아온다고 생각하시면 됩니다.
이후 service코드에서 repository를 호출하여 데이터를 DB에 저장합니다.
service코드
public Long joinUser(JoinRequestDTO dto) {
return userRepository.save(User.builder()
.email(dto.getEmail())
.name(dto.getName())
.password(bCryptPasswordEncoder.encode(dto.getPassword()))
.build()).getId();
}
repository코드
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
User getByEmail(String email);
User findUserByEmail(String email);
Boolean existsByEmail(String email);
//User findByEmailContaining(String keyword);
List<User> findByEmailContainingAndEmailNot(String keyword, String userEmail);
void deleteByEmail(String email);
}
위 repository 코드를 보시면 save method가 없는데, save는 JpaRepository에서 기본적으로 제공하는 메소드로 따로 구현하지 않으셔도 됩니다.
2) Read
@GetMapping("read/notice/user")
public List<RNoticeDTO> readUserNotice(@RequestParam("userEmail") String userEmail){
return noticeService.getReadUserNotice(userEmail);
}
해당 Api Method는 유저의 이메일에 따른 게시물을 읽어오기 위한 코드입니다.
@ReuqestParam의 경우 안드로이드에서의 @Query와 짝을 이루는 annotation입니다.
안드로이드에서 @Query를 통해 userEmail값을 보내면 @RequestParam을 통해 userEmail 값을 받아오고
받아온 값을 토대로 해당 유저의 notice를 불러오는 것입니다.
이후 service코드에서 repository를 호출해서 JPA Method를 통해 원하는 notice를 불러옵니다.
service코드
@Override
public List<RNoticeDTO> getReadUserNotice(String userEmail){
String formattedEmail = "\"" + userEmail + "\"";
// 큰따옴표가 포함된 email로 검색
List<Notice> entities = noticeRepository.findByUserEmail(formattedEmail);
List<RNoticeDTO> dtos = new ArrayList<>();
for (Notice entity : entities) {
RNoticeDTO noticeDTO_R = new RNoticeDTO();
noticeDTO_R.setNoticeId(entity.getNoticeId()); //test
noticeDTO_R.setUserEmail(entity.getUserEmail());
noticeDTO_R.setNoticeTitle(entity.getNoticeTitle());
noticeDTO_R.setNoticeText(entity.getNoticeText());
noticeDTO_R.setNoticeImgPath(entity.getNoticeImg());
noticeDTO_R.setDate(entity.getDate());
dtos.add(noticeDTO_R);
}
return dtos;
}
3) Update
@PutMapping("security/update/{userEmail}")
public ResponseEntity<String> updateUser(
@PathVariable("userEmail") String userEmail,
@RequestPart("userNickName") String userNickName,
@RequestPart("userText") String userText,
@RequestPart("userImg") MultipartFile file
){
if(file.isEmpty()){
return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST);
}
try {
String fileName = file.getOriginalFilename();
UserRequestDTO userJoinRequestDTO = new UserRequestDTO();
userJoinRequestDTO.setUserEmail(userEmail);
userJoinRequestDTO.setUserNickName(userNickName);
userJoinRequestDTO.setUserText(userText);
userJoinRequestDTO.setUserImg(file);
userService.updateUser(userEmail, userJoinRequestDTO);
return new ResponseEntity<>("File uploaded successfully: " + fileName, HttpStatus.OK);
} catch (Exception e){
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PathVariable의 경우 안드로이드의 @Path와 짝을 이루는 annotation입니다.
@RequestPart는 Spring MVC에서 멀티파트 요청의 일부를 메서드의 파라미터로 매핑할 때 사용하는 어노테이션입니다. 주로 파일 업로드와 같은 멀티파트 요청에서 사용되며, HTTP 요청의 본문에 포함된 데이터 중에서 특정 부분을 추출하여 메서드에서 사용할 수 있게 해줍니다.
예륻들어 @RequestPart("userNickName")은 멀티파트 요청에서 "userNickName" 부분을 추출하여 userNickName 파라미터로 전달합니다
더 자세한 내용은 추후 안드로이드 에뮬레이터에서 스프링 서버로 이미지 upload & download편에서 작성하도록 하겠습니다.
ResponseEntity는 Spring MVC에서 HTTP 응답을 표현하는 데 사용되는 클래스입니다. 이 클래스는 HTTP 응답의 상태 코드, 헤더 및 본문을 설정할 수 있도록 해줍니다.
위의 코드에서 ResponseEntity는 응답 본문에 "File uploaded successfully"라는 메시지를 포함하고, HTTP 상태 코드는 200 OK를 설정합니다.
안드로이드에서는 이를 ResponseBody를 이용해 받아옵니다.
service코드의 경우 위 코드들과 비슷한 형식으로 작동하므로 생략하겠습니다.
4) Delete
//회원탈퇴
@DeleteMapping("delete/{userEmail}")
public ResponseEntity<String> deleteUser(@PathVariable("userEmail") String userEmail) {
if (userEmail == null || userEmail.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User email not provided");
}
try {
userService.deleteUserByEmail(userEmail);
return ResponseEntity.ok("success");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
}
}
Delete Method에 대한 설명은 위에서 설명한 내용을과 유사하므로 생략하겠습니다.
이렇게 Retrofit2를 이용한 안드로이드와 스프링 서버 통신 스프링편을 마무리하겠습니다.
다음번에는 글에서 말씀드린것처럼 image upload & download in emulator android & spring (android)이라는 주제로 돌아오겠습니다.
긴 글 봐주셔서 감사합니다.
'Spring실습' 카테고리의 다른 글
Spring에서 security 적용 방법과 자동 로그인 구현 (0) | 2024.10.18 |
---|---|
Spring security + jwt를 이용하여 로그인 구현하기(3) (0) | 2023.07.01 |
Spring Security + jwt를 이용하여 로그인 구현하기(2) (0) | 2023.06.26 |
Spring Security + jwt를 이용하여 로그인 구현하기(1) (0) | 2023.06.24 |
스프링부트에서 Validation사용하기(@Valid) (0) | 2023.06.02 |