//상품 수정
@GetMapping("/{itemId}/edit")
public String editForm(@PathVariable Long itemId, Model model){
Item item = itemRepository.findById(itemId);
model.addAttribute("item", item);
return "basic/editForm";
}
정직 리소스를 사용하면 노출 위험이 있으니 보안과 동적 콘텐츠 생성할 수 있는 컨트롤러와 뷰 템플릿으로 개발해보자
뷰 템플릿?
HTML 과 비슷하지만 서버 측에서 동적으로 생성되며 클라이언트에게 전달된다. 그러므로 클라이언트에게 전달하기 전에 템플릿을 처리하여 필요한 데이터를 삽입해준다 위치는 주로 /resources/templates 에 위치한다.
items.html 정적 HTML을 뷰 템플릿(templates) 영역으로 복사하기
/resources/static/items.html → 복사 → /resources/templates/basic/items.html
컨트롤러 의존성 주입(Dependency Injection) 간편화하기
[ BasicItemController ]
@Controller
@RequestMapping("/basic/items")
public class BasicItemController {
private final ItemRepository itemRepository;
//생성자
@Autowired
public BasicItemController(ItemRepository itemRepository){
this.itemRepository = itemRepository;
}
}
@Autowired
public BasicItemController(ItemRepository itemRepository){
this.itemRepository = itemRepository;
}
스프링에서 해당 생성자가 @Autowired 로 의존관계를 주입해주는데 생성자가 하나밖에 없으면 @Autowired를 생략가능하다
@RequiredArgsConstructor
final 이 붙은 멤버변수만 사용해서 생성자를 자동으로 만들어주는 어노테이션
따라서 private final ItemRepository itemRepository; 에 final을 지우면 안된다 그럼 itemRepository 의존관계가 주입이 안되기 때문
간결해진 [ BasicItemController ]
@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class BasicItemController {
private final ItemRepository itemRepository;
}
이제 컨트롤러와 뷰 템플릿을 개발하기
1. 상품목록 - 타임리프
컨트롤러 [ BasicItemController ]
@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class BasicItemController {
private final ItemRepository itemRepository;
@GetMapping
public String items(Model model) {
List<Item> items = itemRepository.findAll();
model.addAttribute("items", items);
return "basic/items";
}
}
데이터가 없는 상태이니까 테스트용으로 데이터를 넣어보기
//테스트용 데이터 추가
@PostConstruct
public void init(){
itemRepository.save(new Item("itemA", 1000,10));
itemRepository.save(new Item("itemB", 2000,20));
}