Wednesday, October 9, 2019

Web context objects: #httpServletRequest & #httpSession in Thymeleaf

Recently while working on a web application developed using Spring Boot & Thymeleaf, I came to know that Thymeleaf provides direct access to #httpServletRequest & #httpSession objects inside a web environment. These objects are also known as Web context objects. Today we would be discussing these objects and their usages with examples.
  • #httpServletRequest: It provides direct access to the javax.servlet.http.HttpServletRequest object associated with the current request.
    ## Usages
    ${#httpServletRequest.getParameter('foo')}
    ${#httpServletRequest.getAttribute('foo')}
    ${#httpServletRequest.getContextPath()}
    ${#httpServletRequest.getRequestName()}
    
    ## use case while using Script Inlining Feature of Thymeleaf
    <script th:inline="javascript" type="text/javascript">
    /*<![CDATA[*/
        ...
        var assignmentId = /*[[${#httpServletRequest.getParameter('assignmentid')}]]*/ 0;
    
    /*]]>*/
    </script>
    
    ## another example 
    <a th:if="${#httpServletRequest.getParameter('assignmentid') != null} and ${#httpServletRequest.requestURI eq '/studentassignment'}" 
       th:href="@{${#httpServletRequest.requestURI}(isbn=${bookModel.isbn},assignmentid=${#httpServletRequest.getParameter('assignmentid')})}"   
       th:text="${'Test Link'}">Test Link</a>
    
  • #httpSession: It provides direct access to the javax.servlet.http.HttpSession object associated with the current request.
    ## Usages
    ${#httpSession.getAttribute('foo')}
    ${#httpSession.id}
    ${#httpSession.lastAccessedTime}
Hoping that it might be useful for you guys. Happy Learning!! ☺

No comments:

Post a Comment