Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a service method with Thymeleaf

As we can call service method in a jsp as follow(say to check authorization) :

<sec:authorize var="hasLicense" access="@licenseService.hasCapability('Event')"/>

How can we call this method when using Thymeleaf?

I know, We can check role as follow but couldn't get an example for above case:

<li class="link" sec:authorize="hasRole('event')">
like image 498
John Avatar asked May 08 '17 06:05

John


2 Answers

Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName syntax, for example:

<div th:text="${@urlService.getApplicationUrl()}">...</div>

http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

So this should work:

<li class="link" sec:authorize="${@licenseService.hasCapability('Event')}">
like image 161
benkuly Avatar answered Oct 23 '22 13:10

benkuly


For you to call your service methods from your Thymeleaf template you need to add that service into your model like so

@Controller
public class PageController {

    @Autowired
    LicenseService licenseService;

    @RequestMapping("/yourPage")
    public String getYourPage(Model model) {
        model.addAttribute("licenseService", licenseService);
        return "yourPage.html";
    }

}

After that you are good to use licenseService in yourPage.html.

<div th:if="${licenseService.verifyLicense() == true}">
    <p> License verified </p>
</div>
like image 28
Abdullah Khan Avatar answered Oct 23 '22 14:10

Abdullah Khan