예1)
@Controller
@RequiredArgsConstructor
public class CartController {
private final CartService cartService;
@PostMapping(value = "/cart")
@ResponseBody
public ResponseEntity order(@RequestBody @Valid CartItemDto cartItemDto, BindingResult bindingResult, Principal principal){
if(bindingResult.hasErrors()){
StringBuilder sb =new StringBuilder();
List<FieldError> fieldErrors =bindingResult.getFieldErrors();
for(FieldError fieldError :fieldErrors){
sb.append(fieldError.getDefaultMessage());
}
return new ResponseEntity<String>(sb.toString(), HttpStatus.BAD_REQUEST);
}
String email =principal.getName();
Long cartItemId;
try {
cartItemId =cartService.addCart(cartItemDto, email);
}catch (Exception e){
return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Long>(cartItemId, HttpStatus.OK);
}
}
$(document).ready(function(){
calculateToalPrice();
$("#count").change( function(){
calculateToalPrice();
});
});
function calculateToalPrice(){
var count = $("#count").val();
var price = $("#price").val();
var totalPrice = price*count;
$("#totalPrice").html(totalPrice + '원');
}
function order2(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var url = "/order";
var paramData = {
itemId : $("#itemId").val(),
count : $("#count").val()
};
var param = JSON.stringify(paramData);
$.ajax({
url : url,
type : "POST",
contentType : "application/json",
data : param,
beforeSend : function(xhr){
/* 데이터를 전송하기 전에 헤더에 csrf값을 설정 */
xhr.setRequestHeader(header, token);
},
dataType : "json",
cache : false,
success : function(result, status){
alert("주문이 완료 되었습니다.");
location.href='/';
},
error : function(jqXHR, status, error){
if(jqXHR.status == '401'){
alert('로그인 후 이용해주세요');
location.href='/members/login';
} else{
alert(jqXHR.responseText);
}
}
});
}
function order(){
var token=$("meta[name='_csrf']").attr("content");
var header=$("meta[name='_csrf_header']").attr("content");
var url="/order";
var paramData={
itemId:$("#itemId").val(),
count:$("#count").val()
}
var param=JSON.stringify(paramData);
$.ajax({
url:url,
type:"POST",
contentType:"application/json",
data:param,
beforeSend:function(xhr){
xhr.setRequestHeader(header, token);
},
dataType:"json",
cache:false,
success:function(result, status){
alert("주문이 완료 되었습니다.");
location.href="/";
},
error:function(jqXHR, status, error){
if(jqXHR.status=='401'){
alert('로그인 후 이용해 주세요.');
location.href="/memebrs/login";
}else{
alert(jqXHR.responseText);
}
}
});
}
function addCart(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var url = "/cart";
var paramData = {
itemId : $("#itemId").val(),
count : $("#count").val()
};
var param = JSON.stringify(paramData);
$.ajax({
url : url,
type : "POST",
contentType : "application/json",
data : param,
beforeSend : function(xhr){
/* 데이터를 전송하기 전에 헤더에 csrf값을 설정 */
xhr.setRequestHeader(header, token);
},
dataType : "json",
cache : false,
success : function(result, status){
alert("상품을 장바구니에 담았습니다.");
location.href='/';
},
error : function(jqXHR, status, error){
if(jqXHR.status == '401'){
alert('로그인 후 이용해주세요');
location.href='/members/login';
} else{
alert(jqXHR.responseText);
}
}
});
}
예2)
@ResponseBody
@PostMapping(value = "/cart/orders")
public ResponseEntity orderCartItem(@RequestBody CartOrderDto cartOrderDto, Principal principal){
List<CartOrderDto> cartOrderDtoList=cartOrderDto.getCartOrderDtoList();
if(cartOrderDtoList==null || cartOrderDtoList.size()==0){
return new ResponseEntity<String>("주문할 상품을 선택해주세요.",HttpStatus.FORBIDDEN);
}
for(CartOrderDto cartOrder :cartOrderDtoList){
if(!cartService.validateCartItem(cartOrder.getCartItemId(), principal.getName())){
return new ResponseEntity<String>("주문 권한이 없습니다.", HttpStatus.FORBIDDEN);
}
}
Long orderId=cartService.orderCartItem(cartOrderDtoList, principal.getName());
return new ResponseEntity<Long>(orderId, HttpStatus.OK);
}
function orders(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var url="/cart/orders";
var dataList=new Array();
var paramData=new Object();
$("input[name=cartChkBox]:checked").each(function(){
var cartItemId=$(this).val();
console.log(" cartItemId :" +cartItemId);
var data=new Object();
data["cartItemId"]=cartItemId;
dataList.push(data);
});
paramData['cartOrderDtoList']=dataList;
var param =JSON.stringify(paramData);
$.ajax({
url:url,
type:"POST",
contentType:"application/json",
data:param,
beforeSend:function(xhr){
xhr.setRequestHeader(header, token);
},
dataType:"json",
cache:false,
success:function(result, status){
alert("주문이 완료 되었습니다.");
location.href="/orders";
},
error:function(jqXHR, status, error){
if(jqXHR.status=="401"){
alert("로그인후 이용해주세요.");
}else{
console.log(jqXHR);
alert(jqXHR.responseText);
}
}
});
}











댓글 ( 4)
댓글 남기기