<tr th:each="cartItem : ${cartItems}"> <td class="text-center align-middle"> <input type="checkbox" name="cartChkBox" th:value="${cartItem.cartItemId}"> </td> </tr>
1. js
function orders(){ const token=$("meta[name='_csrf']").attr("content"); const header=$("meta[name='_csrf_header']").attr("content"); const url="/cart/orders"; const dataList=new Array(); const paramData=new Object(); $("input[name=cartChkBox]:checked").each(function(){ const cartItemId=$(this).val(); const data=new Object(); data["cartItemId"]=cartItemId; dataList.push(data); }) paramData["cartOrderDtoList"]=dataList; const param=JSON.stringify(paramData); console.log("dataList : ",dataList); console.log("paramData : ",dataList); $.ajax({ url:url, type:"POST", beforeSend:function (xhr){ // 데이터를 전송하기 전에 헤더에 csrf값을 설정 xhr.setRequestHeader(header,token); }, dataType:"json", cache:false, contentType:"application/json", data:param, success:function(result,status){ alert("주문이 완료 되었습니다."); location.href="/orders"; }, error:function(jqXHR, status, error){ console.log(" 에러 : jqXHR : ", jqXHR, " =====status: ", status, " ===== error: ", error); if(jqXHR.status =='401'){ alert("로그인 후 이용해주세요."); location.rhref="/members/login"; }else{ alert(jqXHR.responseJSON.message); } } }) }
DTO
import lombok.Getter; import lombok.Setter; import java.util.List; @Setter @Getter public class CartOrderDto { private Long cartItemId; /** 장바구니에서 여러 개의 상품을 주문하므로 CartOrderDto 클래스가 자기 자신을 가지고 있도록 cartOrderDtoList 변수 생성 */ private List<CartOrderDto> cartOrderDtoList; }
3. constroller
/** * 장바구니에서 주문 */ @PostMapping(value = "/cart/orders") @ResponseBody public ResponseEntity<?> orderCartItem(@RequestBody CartOrderDto cartOrderDto, @AuthenticationPrincipal PrincipalDetails principalDetails){ List<CartOrderDto> cartOrderDtoList = cartOrderDto.getCartOrderDtoList(); if(cartOrderDtoList==null || cartOrderDtoList.size()==0){ return ResponseEntity.status(HttpStatus.FORBIDDEN).body("주문할 상품을 선택해 주세요."); } for(CartOrderDto cartOrder : cartOrderDtoList){ if(!cartService.validateCartItem(cartOrder.getCartItemId(), principalDetails.getEmail())){ return ResponseEntity.status(HttpStatus.FORBIDDEN).body("주문 권한이 없습니다."); } } Long orderId=cartService.ordrerCartItem(cartOrderDtoList, principalDetails.getEmail()); return ResponseEntity.status(HttpStatus.OK).body(orderId); }
소스 :https://github.com/braverokmc79/jpa-shop-test2
댓글 ( 0)
댓글 남기기