[Spring_Boot] 상품 목록,등록,수정,상세페이지 / PathVariable/ ModelAttribute/ RedirectAttributes/ RequiredArgsConstructor

최현석·2022년 11월 27일
0

Spring_Boot

목록 보기
9/31

🧩 @postConstruct

  • 객체의 초기화 부분
  • 객체가 생성된 후 별도의 초기화 작업을 위해 실행하는 메소드를 선언한다.
  • WAS가 띄워질 때 실행된다.

🧩 @PreDestroy

  • 마지막 소멸 단계

🧩 경로 이동

  • context path를 추가해서 이동
  • 프로젝트이름/index.html
    프로젝트이름/user/userMain.jsp
  • /

🧩 @PathVariable

  • (@PathVariable("name")) 값을 String name 변수로 받아옴
  • RequestParam
    http://192.168.0.1:8080?aaa=bbb&ccc=ddd
  • PathVariable
    http://192.168.0.1:8080/bbb/ddd
 @GetMapping("/member/{name}")
 public String memberFind(@PathVariable("name") String name){
	
 }
 생략가능
 public String memberFind(@PathVariable String name){
	
 }

// 여러개
@GetMapping("/member/{id}/{name}")
public String memberFind(@PathVariable("id") String id,
							@PathVariable("name") String name){
}

🧩 @ModelAttribute

  • 요청 파라미터 처리
    -> Item 객체를 생성하고, 요청 파라미터의 값을 프로퍼티 접근법
    (set..) 으로 입력해준다.
    -> model.addAttribute("item",item); 대신
    -> @ModelAttribute("이름 설정")

🧩 RedirectAttributes

  • redirect 할 때 사용될 수 있는 여러 속성값을 컨트롤
  • 리다이렉트를 통해 페이지를 이동하는 것은 좋은데, 이 경우 내가 수행한 로직(상품 등록, 상품 수정 등) 이 정상적으로 완료되었는지를 알 수 없다. 그래서 리다이렉트 된 페이지에 이런 결과를 노출하고싶을 때 RedirectAttributes를 이용하면 된다.
  • URL 인코딩 뿐아니라 PathVariable, 쿼리파라미터 처리까지 해준다.

🧩 RequiredArgsConstructor

  • @RequiredArgsConstructor
    -> final이 붙은 멤버변수만 사용해서 생성자를 자동으로 만들어준다

🧩상품 페이지 실습

item

@Getter @Setter
public class Item {
	private Long id;
	private String itemName;
	private Integer price;
	private Integer quantity;
	
	public Item() {}

	public Item( String itemName, Integer price, Integer quantity) {
		super();
		this.itemName = itemName;
		this.price = price;
		this.quantity = quantity;
	}
}

ItemRepository

@Repository
public class ItemRepository {
	// DB가 아닌 메모리에서 실행
	// static 사용, 
	private static final Map<Long, Item> store = new HashMap<Long, Item>();
	private static long sequence = 0L;
	
	// 저장
	public Item save(Item item) {
		item.setId(++sequence);
		store.put(item.getId(), item);
		return item;
	}
	
	// id로 찾기
	public Item findById(Long id) {
		return store.get(id);
	}
	
	// 전체 찾기
	public List<Item> findAll(){
		return new ArrayList<Item>(store.values());
	}
	
	// 수정
	// itemId를 기준으로 updateParam값을 받아온다(수정을 원하는 item값)
	public void update(Long itemId, Item updateParam) {
		// item을 먼저 찾는다.
		Item findItem = findById(itemId);
		findItem.setItemName(updateParam.getItemName());
		findItem.setPrice(updateParam.getPrice());
		findItem.setQuantity(updateParam.getQuantity());
	}
	
}

ItemController

@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
// @RequiredArgsConstructor 
// : final이 붙은 멤버변수만 사용해서 생성자를 자동으로 만들어준다
public class ItemController {

	private final ItemRepository itemRepository;
	
//	@Autowired
	// 생성자 1개만 있으면 생략 가능
//	public ItemController(ItemRepository itemRepository) {
//		this.itemRepository = itemRepository;
//	}
	
	@GetMapping
	// 상품 목록 페이지 전체 select후 화면에 뿌려주다
	// @RequestMapping("/basic/items") 이유로 메핑해줄게 없음
	public String items(Model model) {
		List<Item> items = itemRepository.findAll();
		model.addAttribute("items", items);
		return "basic/items";
	}
	
	// url : /basic/item/아이템의ID 넘어온다 
	@GetMapping("/{itemId}")
	// 고정된 값이 아니므로 변수로 받아온다
	// 패스에 변수처럼 담겨있는 내용은 @PathVariable
	public String item(@PathVariable long itemId, Model model) {
		Item item = itemRepository.findById(itemId);
		model.addAttribute("item",item);
		return "basic/item";
	}

	
	@GetMapping("/add")
	public String addForm() {
		return "basic/addForm";
	}
	
//	@PostMapping("/add")
	public String save( @RequestParam String itemName,
						@RequestParam int price,
						@RequestParam Integer quantity,
						Model model) {
		Item item = new Item();
		item.setItemName(itemName);
		item.setPrice(price);
		item.setQuantity(quantity);
		
		itemRepository.save(item);
		model.addAttribute("item",item);
		
		return "basic/item";
	}
	
	// 받아오는 파라미터 변경
//	@PostMapping("/add")
	public String saveV2(  @ModelAttribute("item")Item item){
		
		// @ModelAttribute 가 해주는 역할
//		Item item = new Item();
//		item.setItemName(itemName);
//		item.setPrice(price);
//		item.setQuantity(quantity);
		
		itemRepository.save(item);
		
//		model.addAttribute("item",item);
		
		return "basic/item";
	}

	
	/*
	 * @ModelAttribute 에서 name 생략
	 *  -> 생략시 model에 저장되는 name은 클래스명 첫 글자만 소문자로 등록
     *  @ModelAttribute Apple apple이면 Model.addAttribute("apple", apple) 와 같다.
	 *  	Item -> item
	 */
//	@PostMapping("/add")
	public String saveV3( @ModelAttribute Item item){
			
		itemRepository.save(item);
		
		return "basic/item";
	}

	/*
	 *  @ModelAttribute 생략 가능, 그러나 가독성을 위해 권장 X
	 *  비추! 버전 2, 3 까지 추천
	 */
//	@PostMapping("/add")
	public String saveV4(Item item){
		itemRepository.save(item);
		return "basic/item";
	}

	@PostMapping("/add")
	public String saveV5(Item item){
		itemRepository.save(item);
		return "redirect:/basic/items/" + item.getId();
	}
	
	
	/*
	 * redirect:/basic/items/{itemId}
	 *  -> @PathVariable	: {itemId} 메핑이되는 부분
	 *  -> 나머지 파라미터로 처리	: ?status=true
	 */
//	@PostMapping("/add")
	public String saveV6(Item item, RedirectAttributes redirectAttributes){
		Item saveItem = itemRepository.save(item);
		
		redirectAttributes.addAttribute("itemId", saveItem.getId());
		redirectAttributes.addAttribute("status", true);
        // 컨트롤러에 매핑된 @PathVariable의 값인 itemId가 그대로 사용되어 매핑된다.
		// return "redirect:/basic/items/" + item.getId();
		return "redirect:/basic/items/{itemId}";
        //	리다이렉트할 때 간단히 status를 추가해 뷰 템플릿에서 th:if 로 결과를 표시할 수 있다. 
		//	⇒ 실행결과 http://localhost:8080/basic/items/3?status=true 가 리다이렉트된다. 

	}


	// 수정 버튼 쿨릭시 editForm, 파라미터 Id 넘어온것으로, item결과 리턴받아 가져온다
	// /{itemId}/edit 에서 /{itemId}는 가변가능한 value값, /edit는 고정값
	@GetMapping("/{itemId}/edit")
	public String editForm(@PathVariable Long itemId, Model model) {
		Item item = itemRepository.findById(itemId);
		model.addAttribute("item",item);
		return "basic/editForm";
	}
	
	@PostMapping("/{itemId}/edit")
	public String edit(@PathVariable Long itemId, @ModelAttribute Item item) {
		itemRepository.update(itemId, item);
		// 상세페이지 이동
        // 상품 수정은 마지막에 뷰 템플릿 호출이 아닌 상품 상세 화면으로 이동하도록 리다이렉트를 호출한다. 
		// 컨트롤러에 매핑된 @PathVariable의 값인 itemId가 그대로 사용되어 매핑된다.
		// redirect: 컨트롤러로 부터 내용이 다시 시작
		return "redirect:/basic/items/{itemId}";
	}
	
	
	
	// 테스트용 데이터 추가
	@PostConstruct
	public void init() {
		System.out.println("초기화 메서드");
		itemRepository.save(new Item("testA",10000,10));
		itemRepository.save(new Item("testB", 20000, 20));
	}
	
	// 종료 메서드
	@PreDestroy
	public void destroy() {
		System.out.println("종료 메서드");
	}
	
}

items

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<link href="./css/bootstrap.min.css"
	th:href="@{/css/bootstrap.min.css}"
	rel="stylesheet">
</head>
<body>
	<div class="container" style="max-width: 600px">
		<div class="py-5 text-center">
			<h2>상품 목록</h2>
		</div>
		<div class="row">
			<div class="col">
				<!-- th:onclick 사용시 원래 것을 덮어 씌운다-->
				<button class="btn btn-primary float-end" 
					onclick="location.href='addForm.html'" 
					th:onclick="|location.href='@{/basic/items/add}'|" type="button">
					상품 등록
				</button>
			</div>
		</div>
		<hr class="my-4">
		<div>
			<table class="table">
				<thead>
					<tr>
						<th>ID</th>
						<th>상품명</th>
						<th>가격</th>
						<th>수량</th>
					</tr>
				</thead>
				<tbody>
					<tr th:each="item : ${items}">
						<td>
							<!-- /basic/item/아이템의ID -->
							<a href="item.html"  
								th:href="@{/basic/items/{itemId}(itemId=${item.id})}" 
								th:text="${item.id}">회원id</a>
						</td>
						<td>
							<!-- /basic/item/아이템의ID -->
							<a href="item.html" 
								th:href="@{|/basic/items/${item.id}|}" 
								th:text="${item.itemName}">상품명</a>
						</td>
						<td th:text="${item.price}"></td>
						<td th:text="${item.quantity}"></td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
	<!-- /container -->
</body>
</html>

item

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<link href="./css/bootstrap.min.css"
	th:href="@{/css/bootstrap.min.css}"
	rel="stylesheet">
<style>
	.container {
		max-width: 560px;
	}
</style>
</head>
<body>
	<div class="container">
		<div class="py-5 text-center">
			<h2>상품 상세</h2>
		</div>
		
		<!-- 추가 -->
		<h2 th:if="${param.status}" th:text="'저장완료!'"></h2>
		<div>
			<label for="itemId">상품 ID</label> 
			<input type="text"   id="itemId" name="itemId" class="form-control" 
				value="1" th:value="${item.Id}"readonly>
		</div>
		<div>
			<label for="itemName">상품명</label> 
			<input type="text"  id="itemName" name="itemName" class="form-control" 
				value="상품A" th:value="${item.itemName}" readonly>
		</div>
		<div>
			<label for="price">가격</label> 
			<input type="text" id="price" name="price" class="form-control" 
				value="10000" th:value="${item.price}" readonly>
		</div>
		<div>
			<label for="quantity">수량</label> 
			<input type="text" id="quantity" name="quantity" class="form-control" 
				value="10" th:value="${item.quantity}" readonly>
		</div>
		<hr class="my-4">
		<div class="row">
			<div class="col">
				<!-- /basic/items/아이템ID/edit -->
				<button class="w-100 btn btn-primary btn-lg" 
					th:onclick="|location.href='@{/basic/items/{itemId}/edit(itemId=${item.Id})}'|"
					onclick="location.href='editForm.html'" type="button">
					상품수정
				</button>	
			</div>
			<div class="col">
				<button class="w-100 btn btn-secondary btn-lg" 
					th:onclick="|location.href='@{/basic/items}'|"
					onclick="location.href='items.html'" type="button">
					목록으로
				</button>
			</div>
		</div>
	</div>
	<!-- /container -->
	
	<script th:inline="javascript">
		if([[${param.status}]]){
			alert("저장완료");
		}
	</script>
</body>
</html>

addForm

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<link href="./css/bootstrap.min.css"
	th:href="@{/css/bootstrap.min.css}"
	rel="stylesheet">
<style>
	
.container {
	max-width: 560px;
}
</style>
</head>
<body>
	<div class="container">
		<div class="py-5 text-center">
			<h2>상품 등록 폼</h2>
		</div>
		<h4 class="mb-3">상품 입력</h4>
		<form action="item.html" th:action="@{/basic/items/add}" method="post">
			<div>
				<label for="itemName">상품명</label> 
				<input type="text" id="itemName" name="itemName" class="form-control" 
					 placeholder="이름을 입력하세요">
			</div>
			<div>
				<label for="price">가격</label> 
				<input type="text" id="price" name="price" class="form-control" placeholder="가격을 입력하세요">
			</div>
			<div>
				<label for="quantity">수량</label> 
				<input type="text" id="quantity" name="quantity" class="form-control" placeholder="수량을 입력하세요">
			</div>
			<hr class="my-4">
			<div class="row">
				<div class="col">
					<button class="w-100 btn btn-primary btn-lg" type="submit">
						상품등록
					</button>
				</div>
				<div class="col">
					<button class="w-100 btn btn-secondary btn-lg" 
					onclick="location.href='items.html'" 
					th:onclick="|location.href='@{/basic/items}'|"
					type="button">
						취소
					</button>
				</div>
			</div>
		</form>
	</div>
	<!-- /container -->
</body>
</html>

editForm

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<link href="./css/bootstrap.min.css"
	th:href="@{/css/bootstrap.min.css}"
	rel="stylesheet">
<style>
.container {
	max-width: 560px;
}
</style>
</head>
<body>
	<div class="container">
		<div class="py-5 text-center">
			<h2>상품 수정 폼</h2>
		</div>
		<form action="item.html" th:action method="post">
			<div>
				<label for="id">상품 ID</label> 
				<input type="text" id="id" name="id" class="form-control" 
					value="1" th:value="${item.Id}" readonly>
			</div>
			<div>
				<label for="itemName">상품명</label> 
				<input type="text" id="itemName" name="itemName" class="form-control" 
					value="상품A" th:value="${item.itemName}">
			</div>
			<div>
				<label for="price">가격</label> 
				<input type="text" id="price" name="price" class="form-control" 
					value="10000" th:value="${item.price}">
			</div>
			<div>
				<label for="quantity">수량</label> 
				<input type="text" id="quantity" name="quantity" class="form-control" 
					value="10" th:value="${item.quantity}">
			</div>
			<hr class="my-4">
			<div class="row">
				<div class="col">
					<button class="w-100 btn btn-primary btn-lg" type="submit">
						저장
					</button>
				</div>
				<div class="col">
					<button class="w-100 btn btn-secondary btn-lg" 
						onclick="location.href='item.html'" 
						th:onclick="|location.href='@{/basic/items/{itemId}(itemId=${item.id})}'|"
						type="button">
						취소
					</button>
				</div>
			</div>
		</form>
	</div>
	<!-- /container -->
</body>
</html>

0개의 댓글