[java] Thymeleaf와 AJAX를 함께 사용하는 방법은 무엇인가요?

Thymeleaf와 AJAX를 함께 사용하는 방법은 다음과 같습니다:

  1. 먼저 pom.xml 파일에 Thymeleaf와 Spring Web 관련 종속성을 추가해야 합니다. 아래는 필요한 종속성 예시입니다: ```xml
org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web

2. Thymeleaf 템플릿에서 AJAX를 사용하기 위해 JavaScript 코드를 작성해야 합니다. 예를 들어, `main.js`라는 파일을 생성하고 아래의 코드를 작성할 수 있습니다:
```javascript
$(document).ready(function() {
    $('#submitBtn').click(function() {
        var inputValue = $('#inputField').val();

        $.ajax({
            type: "POST",
            url: "/process",
            data: {
                inputValue: inputValue
            },
            success: function(response) {
                // 서버로부터 받은 데이터를 처리하는 로직
            },
            error: function(xhr, status, error) {
                // 에러 처리 로직
            }
        });
    });
});
  1. Thymeleaf 템플릿에서 AJAX를 호출할 수 있는 버튼을 추가해야 합니다. 예를 들어, 아래와 같이 코드를 작성할 수 있습니다:
    <input type="text" id="inputField" />
    <button id="submitBtn" onclick="submitForm()">Submit</button>
    
  2. 컨트롤러에서 AJAX 요청을 처리하는 메서드를 작성해야 합니다. 예를 들어, 아래와 같이 코드를 작성할 수 있습니다:
    @Controller
    public class MyController {
    
     @PostMapping("/process")
     public ResponseEntity<String> processAjaxRequest(@RequestParam("inputValue") String inputValue) {
         // AJAX 요청을 처리하는 로직
         return ResponseEntity.ok("Success");
     }
    }
    

이제 Thymeleaf와 AJAX를 함께 사용할 준비가 되었습니다. 위의 예제를 기반으로 하여 원하는 동작을 구현할 수 있습니다. Thymeleaf 템플릿에서도 추상적인 AJAX 요청을 처리할 수 있는 자체적인 기능을 제공하므로, 필요에 따라 그 기능을 사용할 수도 있습니다.

더 자세한 내용은 Thymeleaf와 AJAX에 대한 공식 문서를 참조하시기 바랍니다.