programing

Thymeleaf: 현재 URL에 매개 변수 추가

css3 2023. 7. 4. 22:04

Thymeleaf: 현재 URL에 매개 변수 추가

나는

http://example.com/some/page?p1=11

그리고 다시 정의할 필요 없이 현재 URL에 매개 변수를 추가하고 싶습니다.

http://example.com/some/page?p1=11&p2=32

다음과 같은 것으로:

<a th:href="@{?(p2=32)}">Click here</a>

하지만 위의 코드가 반환됩니다.http://example.com/some/page?&p2=32(계속)p1매개 변수).

Thymeleaf를 사용하여 어떻게 해야 합니까?

Thymeleaf에서 직접 URI Builder를 사용할 수 있습니다.

<span th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder).fromCurrentRequest()}"
      th:text="${urlBuilder.replaceQueryParam('p2', '32').toUriString()}">
</span>

URL의 경우http://example.com/some/page?p1=11출력:

http://example.com/some/page?p1=11&p2=32

설명:

  • SpEL 연산자는 액세스에 사용됩니다.ServletUriComponentsBuilder유형.
  • 공장 방법으로 생성된 인스턴스fromCurrentRequest에 저장됨urlBuilder변수.
  • 쿼리 문자열에 매개 변수가 추가되거나 다음으로 바뀝니다.replaceQueryParam그런 다음 URL이 작성됩니다.

찬성:

  • 안전한 해결책.
  • 후행 없음?쿼리 문자열이 비어 있는 경우.
  • Spring 컨텍스트에서 추가 빈이 없습니다.

단점:

  • 그것은 꽤 장황합니다.

위의 솔루션은 작성자의 인스턴스 하나를 생성합니다.이는 작성기가 여전히 원래 URL을 수정하므로 다시 사용할 수 없음을 의미합니다.페이지에 여러 URL이 있는 경우 다음과 같이 여러 빌더를 만들어야 합니다.

<span th:with="urlBuilder=${T(org.springframework.web.servlet.support.ServletUriComponentsBuilder)}">
    <span th:text="${urlBuilder.fromCurrentRequest().replaceQueryParam('p2', 'whatever').toUriString()}"></span>
    <span th:text="${urlBuilder.fromCurrentRequest().replaceQueryParam('p3', 'whatever').toUriString()}"></span>
    <span th:text="${urlBuilder.fromCurrentRequest().replaceQueryParam('p4', 'whatever').toUriString()}"></span>
</span>

위해서http://example.com/some/page인쇄:

http://example.com/some/page?p2=whatever 
http://example.com/some/page?p3=whatever     
http://example.com/some/page?p4=whatever

가장 쉬운 해결책은 "요청"을 연결하는 것입니다.URI" 및 "queryString"입니다.다음은 예입니다.

<div th:with="currentUrl=(${#httpServletRequest.requestURI + '?' + #strings.defaultString(#httpServletRequest.queryString, '')})">
   <a th:href="@{${currentUrl}(myparam=test)}">click here</a>
</div>

"http://localhost:8080/some-page?param1=1"에 대한 결과:

 http://localhost:8080/some-page?param1=1&myparam=test

"http://localhost:8080/some-page"에 대한 결과:

 http://localhost:8080/some-page?&myparam=test

단점:
Thymeleaf는 매개 변수를 덮어쓰지 않고 URL에 매개 변수만 추가합니다.따라서 해당 URL을 다시 클릭하면 다음과 같은 결과가 나타납니다.

http://localhost:8080/some-page?param1=1&myparam=test&myparam=test

참조:
http://forum.thymeleaf.org/How-to-link-to-current-page-and-exchange-parameter-td4024870.html

편집:

다음은 URL에서 매개 변수 "myparam"을 제거하는 몇 가지 해결 방법입니다.

<div th:with="currentUrl=(${@currentUrlWithoutParam.apply('myparam')})">
    <a th:href="@{${currentUrl}(myparam=test)}">click here</a>
</div>

다음 스프링 구성:

@Bean
public Function<String, String> currentUrlWithoutParam() {
    return param ->   ServletUriComponentsBuilder.fromCurrentRequest().replaceQueryParam(param).toUriString();
}

좀 더 "글로벌" 솔루션을 위해, "th:href" 속성에 대한 프로세서를 확장하거나 나만의 속성을 생성하려고 합니다.저는 타임리프 전문가가 아닙니다. 단지 비슷한 문제에 직면했을 뿐입니다.

th:href="@{/your/link?parameter=__${appendParameter}__}"

문서에 따라 모든 매개변수를 지정할 수 있습니다.

th:href="@{http://example.com/some/page(p1=11,p2=32)}"

식을 사용하여 값을 가져올 수 있습니다.

th:href="@{http://example.com/some/page(p1=11,p2=${someid})}"

이것은 유니코드에서도 사용할 수 있습니다.

 <ul class="pagination">
                <li th:if="${currentPage > 1}"><a th:href="'/search?key=' + ${param.key[0]} + '&amp;page=' +   ${currentPage-1}">Previous</a></li>

                      <li th:each="i : ${#numbers.sequence( 1, total+1)}" th:class="${i==currentPage}?active:''">
                            <a th:href="'/search?key=' + ${param.key[0]} + '&amp;page=' +   ${i}" th:inline="text">
                            [[${i}]] <span  class="sr-only">(current)</span>
                            </a>
                      </li>
                      <li><a th:if="${total + 1 > currentPage}" th:href="'/search?key=' + ${param.key[0]} + '&amp;page=' +   ${currentPage+1}">Next</a></li>
            </ul>

Raf의 답변바탕으로 다음과 같은 해결책을 얻었습니다.

@Bean
public BiFunction<String, String, String> replaceOrAddParam() {
  return (paramName, newValue) -> ServletUriComponentsBuilder.fromCurrentRequest()
        .replaceQueryParam(paramName, newValue)
        .toUriString();
}
<a th:href="${@replaceOrAddParam.apply('myParamName', 'myNewValue')}">Text</a>

언급URL : https://stackoverflow.com/questions/27623405/thymeleaf-add-parameter-to-current-url