본문 바로가기

SpringBoot/스파르타 웹개발의 봄 spring

[스파르타 웹개발의 봄 spring] 04.15 관심상품 최저가 업데이트하기

728x90
반응형

##basic.js 에서 setMyprice()함수 정의

: 웹의 최저가 입력창에 입력하면 setMyprice()가 나의 최저가를 업데이트

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
function setMyprice() {
    /**
    * myprice 값 설정하기.
     * 1. id가 myprice 인 input 태그에서 값을 가져온다
     * 2. 만약 값을 입력하지 않았으면 alert를 띄우고 중단한다.
     * 3. PUT /api/product/${targetId} 에 data를 전달한다.
     *    주의) contentType: "application/json",
     *         data: JSON.stringify({myprice: myprice}),
     *         빠뜨리지 말 것!
     * 4. 모달을 종료한다. $('#container').removeClass('active');
     * 5, 성공적으로 등록되었음을 알리는 alert를 띄운다.
     * 6. 창을 새로고침한다. window.location.reload();
     */
    //1. id가 myprice 인 input 태그에서 값을 가져온다
    let myprice = $('#myprice').val();
    //2. 만약 값을 입력하지 않았으면 alert를 띄우고 중단한다.
    if(myprice == ''){
        alert("값을 입력하세요.");
        return;
    }
    // 3. PUT /api/product/${targetId} 에 data를 전달한다
    $.ajax({
        type: "PUT",
        url: `/api/products/${targetId}`,
        contentType: "application/json",
        data: JSON.stringify({myprice: myprice}),
        success: function (response){
            // 4. 모달을 종료한다. $('#container').removeClass('active');
            $('#container').removeClass('active');
            console.log("관심상품 최저가 PUT 성공");
            // 5, 성공적으로 등록되었음을 알리는 alert를 띄운다.
            alert("관심상품의 최저가가 성공적으로 업데이트 되었습니다.")
            // 6. 창을 새로고침한다. window.location.reload();
            window.location.reload();
        }
    })
 
 
 
}
cs

 

##ProductRestController.java

-PUT jquery 로 작동하는 PUT 컨트롤러 작성하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RestController // json 형식 컨트롤러
@RequiredArgsConstructor // 의존주입 생성자 -> final 변수에 적용
public class ProductRestController {
 
    private final ProductRepository productRepository;
    private final ProductService productService;
 
    // 상품조회한 목록 불러오기
    @GetMapping("/api/products")
    public List<Product> readProducts(){
       return productRepository.findAll();
    }
 
    // 관심상품 등록하기
    @PostMapping("/api/products")
    public Product createProduct(@RequestBody ProductRequestDto requestDto){ //@RequestBody
        Product product = new Product(requestDto);
        return productRepository.save(product);
    }
 
    // 관심상품 최저가 업데이트
    @PutMapping("/api/products/{id}")
    public Long updateProduct(@PathVariable Long id, @RequestBody ProductMypriceRequestDto requestDto){
        return productService.update(id,requestDto);
    }
 
 
}
 
cs

 

반응형