0

Somewhere in my code, I'm adding an attribute into the session.

session.setAttribute("message", message);

And in my HTML file, I want to remove it right after I comsume it.

<div th:if="${session.message != null}">
   // consume message
   // remove message from session.
</div>

How do I do that?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
oxyt
  • 1,816
  • 3
  • 23
  • 33
  • You can't... instead, you should use flash attributes in cases like this: https://stackoverflow.com/a/44488706/4126893 -- they'll disappear for you automatically. – Metroids Apr 28 '19 at 14:41

2 Answers2

0

I solved my problem. Created a component with this method.

public void removeVerificationMessageFromSession() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            session.removeAttribute("verificationMessage");
        } catch (RuntimeException ex) {
            log.error("No Request: ", ex);
        }
    }

and then I called this method in my code right after I consumed the message.

<div th:if="${session.message != null}">
   // I consumed the message
   <div th:text="${@sessionUtilityBean.removeVerificationMessageFromSession()}"></div>
</div>
oxyt
  • 1,816
  • 3
  • 23
  • 33
0

I successfully used

 <th:block th:inline="text"> [[${#session.removeAttribute('variableName')}]]</th:block>
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
Manikandan TK
  • 33
  • 1
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 12 '22 at 14:51