메모 삭제 기능을 구현하기 위해 MemoController 클래스에 delete() 함수를 추가합니다.
이 함수는 URL 경로에서 전달된 메모의 ID를 받아 DAO의 삭제 메서드를 호출한 후, 메모 목록 페이지로 리디렉션합니다.
▼ Code
package com.example.memo;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class MemoController {
@Autowired
private MemoDAO memoDao;
@GetMapping("/")
public String list(Model model) {
List<Map<String, Object>> memos = memoDao.list();
model.addAttribute("memos", memos);
return "list";
}
@GetMapping("/write")
public String write() {
return "write";
}
@PostMapping("/insert")
public String insert(@RequestParam Map<String, Object> memo) {
memoDao.insert(memo);
return "redirect:/";
}
@GetMapping("/edit/{id}")
public String edit(@PathVariable(name = "id") int id, Model model) {
Map<String, Object> memo = memoDao.detail(id);
model.addAttribute("memo", memo);
return "edit";
}
@PostMapping("/update")
public String update(@RequestParam Map<String, Object> memo) {
memoDao.update(memo);
return "redirect:/";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable(name = "id") int id) {
memoDao.delete(id);
return "redirect:/";
}
}
▼ Explain
@GetMapping("/delete/{id}") 클라이언트가 /delete/5 와 같은 URL로 GET 요청을 보내면 실행됩니다. {id}는 경로 변수로, 삭제할 메모의 고유 ID를 의미합니다. public String delete(@PathVariable(name = "id") int id) { @PathVariable은 URL 경로에 포함된 {id} 값을 변수 id에 자동으로 바인딩합니다. 즉, /delete/5 요청이 오면 id 값은 5가 됩니다. memoDao.delete(id); MemoDAO의 delete(int id) 메서드를 호출하여 ID에 해당하는 메모를 데이터베이스에서 삭제합니다. return "redirect:/"; 삭제 작업이 끝난 후, 메모 목록 페이지(/)로 리디렉션합니다.
개인정보처리방침 · 이용약관