목록백/spring (18)
개발새발 블로그

- 트랜잭션 : 모두 성공해야 하는 일련의 과정(순서) - 롤백 : 트랜잭션이 실패가 될 경우 진행 초기상태로 다시 돌리는 것. @Slf4j @Service public class ArticleService { @Autowired private ArticleRepository articleRepository; public List index() { return articleRepository.findAll(); } public Article show(Long id) { return articleRepository.findById(id).orElse(null); } public Article create(ArticleForm dto) { Article article = dto.toEntity(); //AP..

REST API로 요청과 응답을 주고받을 때는 REST 컨트롤러를 사용한다. 기존의 컨트롤러 파일에서는 @Controller 를 사용했지만, API로 응답을 주고받을때는 @RestController를 사용한다. @RestController //REST API용 컨트롤러 public class FirstApiController { @GetMapping("/api/hello") public String hello(){ return "hello world!"; } } 이렇게 리턴값으로 보내주면 응답 body에 리턴값 그대로 hello world! 가 찍히는 것을 확인할 수 있다. 기존의 그냥 컨트롤러와 어떤 차이가 있냐면, 기존에는 return "greetings"; 처럼 mustache 뷰 파일을 반환하도록..

Delete 지난 포스트에서 만들었던 수정버튼 옆에 삭제버튼도 만든다. HTML 에서 POST와 GET만 지원하고, DELETE는 지원하지 않아서 @DeleteMapping 이 아닌 @GetMapping으로 적어주겠다. @GetMapping("articles/{id}/delete") public String delete(@PathVariable Long id, Model model){ Article target = articleRepository.findById(id).orElse(null); if(target != null){ articleRepository.delete(target); } return "redirect:/articles"; } 2번 id의 내용이 삭제된 것을 확인할 수 있다!! 와!!..

1. 수정 페이지 만들기 Edit id당 하나씩만 보여주는 상세페이지에서, edit 버튼을 누르면 삭제할 수 있도록 링크를 건다. 그런데, 이전의 포스팅에서 {{#article}} {{/article}} 사용범위를 지정해놓고 {{id}} , {{title}} 이렇게 변수를 사용했었는데, 사용범위를 따로 지정하지 않는 경우에는 {{articles.id}} 이렇게 사용한다. @GetMapping("articles/{id}/edit") public String edit(@PathVariable Long id, Model model){ Article articleEntity = articleRepository.findById(id).orElse(null); model.addAttribute("article", ..

New Article 5장 기존에 작성했던 모든 목록을 보여주는 articles 페이지에 새 글을 작성할 수 있는 articles/new 링크를 추가한다. Back 마찬가지로 articles/new 페이지에서도 목록을 볼 수 있는 articles 링크를 추가한다. 여기서 아까 만들었던 Back 버튼을 누르면 정상 실행이 되고, 추가로 Submit 버튼을 눌렀을 때도 목록 링크가 뜨면 좋겠지만, 지금은 WhiteLabel 오류가 뜬다. 이때 사용하는 개념이 리다이렉트다. @PostMapping("/articles/create") public String createArticle(ArticleForm form) { Article article = form.toEntity(); Article saved = a..

데이터를 받아서 db에 저장하는 작업까지 수행했다. 이제는 데이터를 조회하는 작업을 할 것이다. 1번 id를 조회할 때 localhost:8080/articles/1, 2번 id를 조회할 때 localhost:8080/articles/2 이렇게 접속하는 식으로 URL 요청을 받을 것이다. @GetMapping("/articles/{id}") public String show(@PathVariable Long id){ log.info("id = " + id); return ""; } GetMapping 으로 해당 id값을 주소로 받아서, 메소드의 매개변수로 @PathVariable을 붙이면 URL으로 들어온 id 값을 컨트롤러의 매개변수로 가져오는 어노테이션이다. 현재 코드에서 localhost:8080/..