Displaying Content in Thymeleaf When User NOT in a Role

In NixMash Spring v0.3.4 we’re adding a reminder to the Add Post page to remind users the post will not be saved or displayed. We only want to display that message to users not in the ROLE_POSTS group. As you can see from the title, the key phrase here is “when the user is NOT in a role.”

We’re using the Thymeleaf Spring Security4 libraries as you see in the build.gradle.

To use Thymeleaf Security we add the sec XML Namespace in our HTML Document Declaration.

Now we’re ready to rock, but only with extreme appreciation to MR EXCLAMATION POINT.

The humble exclamation point isn’t advertised much in Thymeleaf documentation, though you will notice it in the Standard Expression Syntax area of the Using Thymeleaf Guide for “negation.” I guess it’s one of things programmers assume all languages support. Regardless, it is our solution to displaying content when the user is NOT in a specific role.

The CurrentUser Alternative

In NixMash Spring we always have access to our custom currentUser Principal on all pages from our Spring @AdviceController. I think you’ll agree that in this case using Thymeleaf Spring Security4 is cleaner. We can still use the Exclamation Point, but we have to add the Question Marks to both the currentUser and user objects to test if they are null to avoid a Thymeleaf Null Object Exception.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.