tuter77

게시판 만들기(7) - 저장, 삭제 기능 구현 본문

GroupStudy

게시판 만들기(7) - 저장, 삭제 기능 구현

tuter77 2023. 1. 29. 20:38

● 저장, 삭제 기능 구현.

 

▷ 저장 html 페이지

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>헬스장 정보 저장 페이지</title>
</head>

<body>
<table>
    <form th:action="@{/write/post}" method="post">
        <p>아래에 자료를 입력하세요.</p>
            <tr>
                <td><input type="text" name="brand_name"></td>
            </tr>
            <tr>
                <td><input type="text" name="land_number"></td>
            </tr>
            <tr>
                <td><input type="text" name="road_number"></td>
            </tr>
            <tr>
                <td><input type="text" name="category"></td>
            </tr>
            <td><input type="reset" value="취소"></td>
            <td><button type="submit">저장</button></td>
        </tr>
    </form>
</table>
</body>
</html>

▷컨트롤러 저장 메서드

@RequiredArgsConstructor
@Controller
@Slf4j
public class HomeController {
    private final HealthRepository healthRepository;
    private final HomeService homeService;
 
 	@GetMapping("/write") // 저장 페이지.
    public String write(){
        return "writer";
    }
  
  	@PostMapping("/write/post") //저장 기능 구현.
    public String writerPost(HealthInfo healthInfo){
        healthRepository.save(HealthInfo.builder()
                .brand_name(healthInfo.getBrand_name())
                .road_number(healthInfo.getRoad_number())
                .land_number(healthInfo.getLand_number())
                .category(healthInfo.getCategory())
                .build());

        return "redirect:/home"; //prg패턴.
    }
}

 

새로운 데이터를 저장하는 것이라 id값을 따로 지정해두지 않고 이전에 healthInfo 엔티티를 생성할 때 @GeneratedValue 어노테이션으로 id값을 자동으로 지정하는 걸 설정해놓은 것을 그대로 사용했다.

 

이후 html파일은 타임리프문을 활용하여, 자료를 저장할 시에 post method로 Post 매핑된 writePost 메서드가 동작하도록 설정했다.

저장 메서드는 healthInfo 객체에 각 값들을 builder로 저장하고 홈html파일을 반환한다.

 

위의 get매핑 write메서드는 writer라는 위의 html파일을 브라우저에 출력하는 용도이다.

 

▷삭제기능

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>상세페이지</title>
</head>

<body>
    <h1 th:text="${healthInfo.brand_name}"></h1>
    <p th:text="${healthInfo.land_number}"></p>
    <p th:text="${healthInfo.road_number}"></p>
    <p th:text="${healthInfo.category}"></p>
    <a th:href="@{/modified{id}(id=${healthInfo.id})}">수정</a>
    <a th:href="@{/home/delete(id=${healthInfo.id})}">삭제</a>
    <button type="submit" onclick="location.href='/home'">뒤로</button>
</body>
</html>
@GetMapping("/home/delete")
    public String healthDelete(@RequestParam Long id){
        homeService.healthDelete(id);
        return "redirect:/home";
    }

삭제기능은 상세페이지의 삭제 태그를 타고 들어가서 실행이 가능하다.

코드를 보면, healthInfo의 id값을통해 저장된 자료를 가져와 delete메서드에 반환해준다.

 delete메서드에서는 반환받은 id값을 delete기능을 통해 지워준다.

homeSerVice의 healthDelete기능은 

@Override
        public boolean healthDelete(@RequestParam Long id){
        healthRepository.deleteById(id);
        return true;
        }

이와 같이 구현되어있다.

JPA레포지토리 의 deleteById메서드를 사용하는것을 볼 수 있다.

해당 healthDelete는 boolean값을 반환하는데 정상적으로 삭제되었을 경우 true를 반환하는 것을 볼 수 있다.

 

위 내용은 2023.01.12에 공부한 내용입니다.

링크 : https://dudwls3278.tistory.com/41