복붙노트

[SPRING] Spring MVC 3.2 Thymeleaf Ajax 파편들

SPRING

Spring MVC 3.2 Thymeleaf Ajax 파편들

Spring MVC 3.2와 Thymeleaf 템플릿 엔진으로 애플리케이션을 구축하고 있습니다. 저는 Thymeleaf의 초심자입니다.

나는 Thymeleaf를 포함하여 모든 작업을하고 있지만 컨트롤러에 단순한 Ajax 요청을하고 결과로 템플릿 (부분)의 일부만 렌더링하는 방법에 대해 간단하고 명확한 설명을 알고 있는지 궁금해하고있었습니다.

내 응용 프로그램은 모든 구성 (스프링 3.2, 봄 보안, thymeleaf, ...) 및 예상대로 작동합니다. 이제 jQuery로 간단하게 Ajax 요청을하고 싶습니다.하지만 Thymeleaf의 튜토리얼 11 장 : 렌더링 템플릿 단편 (링크)에서 파편으로 처리 할 수 ​​있음을 언급 한 이후로 사용하지 않으려하지 않습니다.

현재 내 컨트롤러에 있습니다.

@RequestMapping("/dimensionMenuList")
public String showDimensionMenuList(Model model) {

    Collection<ArticleDimensionVO> articleDimensions;
    try {
        articleDimensions = articleService.getArticleDimension(ArticleTypeVO.ARTICLE_TYPE);
    } catch (DataAccessException e) {
        // TODO: return ERROR
        throw new RuntimeException();
    }

    model.addAttribute("dimensions", articleDimensions);

    return "/admin/index :: dimensionMenuList";
}

    메뉴 항목을 대체하고자하는 부분의보기 :

    <ul th:fragment="dimensionMenuList" class="dropdown-menu">
        <li th:unless="${#lists.isEmpty(dimensions)}" th:each="dimension : ${dimensions}">
            <a href="#" th:text="${dimension.dimension}"></a>
        </li>
    </ul>
    

    어떤 단서가 대단히 감사하겠습니다. 특히 더 이상 프레임 워크를 포함 할 필요가없는 경우. 그것은 이미 너무 많은 자바 웹 응용 프로그램입니다.

    해결법

    1. ==============================

      1.다음은 블로그 게시물에서 발견 한 접근 방식입니다.

      다음은 블로그 게시물에서 발견 한 접근 방식입니다.

      이러한 프레임 워크를 사용하지 않으려 고 jQuery를 사용하여 서버에 AJAX 요청을 보내고 응답을 기다리고 부분적으로 뷰 (조각 렌더링)를 업데이트합니다.

      양식

      <form>
          <span class="subtitle">Guest list form</span>
          <div class="listBlock">
              <div class="search-block">
                  <input type="text" id="searchSurname" name="searchSurname"/>
                  <br />
                  <label for="searchSurname" th:text="#{search.label}">Search label:</label>
                  <button id="searchButton" name="searchButton" onclick="retrieveGuests()" type="button" 
                          th:text="#{search.button}">Search button</button>
              </div>
      
              <!-- Results block -->
              <div id="resultsBlock">
      
              </div>
          </div>
      </form>
      

      이 양식에는 서버로 전송 될 검색 문자열 (searchSurname)이있는 입력 텍스트가 들어 있습니다. 또한 서버에서받은 응답으로 업데이트 될 영역 (resultsBlock div)이 있습니다.

      사용자가 버튼을 클릭하면 retrieveGuests () 함수가 호출됩니다.

      function retrieveGuests() {
          var url = '/th-spring-integration/spring/guests';
      
          if ($('#searchSurname').val() != '') {
              url = url + '/' + $('#searchSurname').val();
          }
      
          $("#resultsBlock").load(url);
      }
      

      jQuery로드 함수는 지정된 URL에있는 서버에 요청을하고 반환 된 HTML을 지정된 요소 (resultsBlock div)에 저장합니다.

      사용자가 검색 문자열을 입력하면 지정된 성을 가진 모든 손님을 검색합니다. 그렇지 않으면 전체 손님 목록을 반환합니다. 이 두 요청은 다음 컨트롤러 요청 매핑에 도달합니다.

      @RequestMapping(value = "/guests/{surname}", method = RequestMethod.GET)
      public String showGuestList(Model model, @PathVariable("surname") String surname) {
          model.addAttribute("guests", hotelService.getGuestsList(surname));
      
          return "results :: resultsList";
      }
      
      @RequestMapping(value = "/guests", method = RequestMethod.GET)
      public String showGuestList(Model model) {
          model.addAttribute("guests", hotelService.getGuestsList());
      
          return "results :: resultsList";
      }
      

      Spring은 Thymeleaf와 통합되었으므로 이제 HTML 조각을 반환 할 수 있습니다. 위의 예에서 반환 문자열 "results :: resultsList"는 결과 페이지에있는 resultsList라는 조각을 나타냅니다. 이 결과 페이지를 살펴 보겠습니다.

      <!DOCTYPE html>
      <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org" lang="en">
      
      <head>
      </head>
      
      <body>
          <div th:fragment="resultsList" th:unless="${#lists.isEmpty(guests)}" id="results-block">
              <table>
                  <thead>
                      <tr>
                          <th th:text="#{results.guest.id}">Id</th>
                          <th th:text="#{results.guest.surname}">Surname</th>
                          <th th:text="#{results.guest.name}">Name</th>
                          <th th:text="#{results.guest.country}">Country</th>
                      </tr>
                  </thead>
                  <tbody>
                      <tr th:each="guest : ${guests}">
                          <td th:text="${guest.id}">id</td>
                          <td th:text="${guest.surname}">surname</td>
                          <td th:text="${guest.name}">name</td>
                          <td th:text="${guest.country}">country</td>
                      </tr>
                  </tbody>
              </table>
          </div>
      </body>
      </html>
      

      등록 된 게스트가있는 테이블 인 조각이 결과 블록에 삽입됩니다.

    2. ==============================

      2.Thymeleaf 조각 만 렌더링해도 ModelAndView와 잘 작동합니다.

      Thymeleaf 조각 만 렌더링해도 ModelAndView와 잘 작동합니다.

      @RequestMapping(value = "/feeds", method = RequestMethod.GET)
      public ModelAndView getFeeds() {
          LOGGER.debug("Feeds method called..");
          return new ModelAndView("feeds :: resultsList");
      }
      
      <!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
      
      <head></head>
      <body>
          <div th:fragment="resultsList" id="results-block">
              <div>A test fragment</div>
              <div>A test fragment</div>
          </div>
      </body>
      </html>
      
      <div id="results-block">
          <div>A test fragment</div>
          <div>A test fragment
          </div>
      </div>
      
    3. ==============================

      3.Sohail의 훌륭한 대답에 대한 대체 버전으로, 자바 스크립트를 사용하여 컨트롤러에 객체를 보내고 양식에 Thymeleaf를 통합하고 @PathVariable을 사용하지 않아도되는 버전을 제공하고자합니다. 당신은 많은 분야와 양식을했습니다.

      Sohail의 훌륭한 대답에 대한 대체 버전으로, 자바 스크립트를 사용하여 컨트롤러에 객체를 보내고 양식에 Thymeleaf를 통합하고 @PathVariable을 사용하지 않아도되는 버전을 제공하고자합니다. 당신은 많은 분야와 양식을했습니다.

      양식의 경우 (id 및 Strings라는 이름을 가진 객체를 반환하는 예제를 사용하고 이러한 객체 중 일부가 값으로 포함 된지도가있는 콤보 상자에 피드)

      <form method="post" th:action="@{/yourMapping}" th:object="${object}" id="yourFormId">
          <select th:field="*{mapOfObjects}">
             <option 
                th:each="entry: ${mapOfObjects}"
                th:value="${entry.value.id}"
                th:text="${entry.value.name}" >
             </option>
          </select>
      
          <p>Name: 
             <input type="text" th:field="*{name}" />
          </p>
      </form>
      

      이 양식이 제출되면 (예 : 제출 유형의 단추를 사용하여) 전체 문서가 대체됩니다. 그러나 우리는 자바 스크립트로 제출을 가로 채고 아약스 방식으로 할 수 있습니다. 이를 달성하기 위해 함수를 사용하여 폼에 인터셉터를 추가합니다. 먼저 양식 뒤에 인터셉터를 추가하는 함수를 호출하십시오.

      <script>formInterceptor("yourFormId");</script>
      

      그리고이 함수는 다음과 같이 보입니다. (문서의 머리 부분이나 필요에 맞는 곳)

      <script>
      function formInterceptor(formName) {
          var $form = $("#" + formName);
      
          $form.on('submit', function(e) {
              e.preventDefault();
              $.ajax({
                  url : $form.attr('action'),
                  type : 'post',
                  data : $form.serialize(),
                  success : function(response) {
                      if ($(response).find('.has-error').length) {
                          $form.replaceWith(response);
                      }
                      else{
                          $("#ajaxLoadedContent").replaceWith(response);
                      }
                  }
              });
          });
      };
      </script>
      

      이제 폼이 제출 될 때마다이 함수가 트리거되고 다음과 같이됩니다.

      교체 된 부품은 다음과 같아야합니다.

      <div id="ajaxLoadedContent"></div>
      

      컨트롤러는 다음과 같이 값이 채워진 형태로 th : 객체를받을 수 있습니다 (객체를 객체 유형으로 바꾸고 "객체"를 적절한 이름으로 바꾸기).

      @PostMapping(value = /yourMapping)
      public String ajaxCtrlExample(@ModelAttribute("object") Object object, Model model) {
          return yourFragmentPath;
      }
      

      그게 전부입니다. ajax 버전에서 필요한 모든 양식 다음에 인터셉터를 추가하는 함수를 호출하십시오.

from https://stackoverflow.com/questions/20982683/spring-mvc-3-2-thymeleaf-ajax-fragments by cc-by-sa and MIT license