Search code examples
javahtmlspringthymeleaf

Spring-Thymeleaf How to invoke with EL an action method from a Bean


I am using Spring/SpringMVC 5.x version, with Thymeleaf and Bootstrap on Tomcat server.

I need to ask something that maybe it might look to you very "st@pid" question.

In my html view I have the following button or a link:

<input type="button" .../>
<a .../>

I don't need to submit something, so I just use a simple button, so I think I don't need any form for it (except if I need for this).

In this html view (because of the thymeleaf library I added in the html tag), I need to add somehow, (but I don't know how), to this button or in the link, an expression of Spring EL or Thymeleaf EL, so I can invoke a method from a Spring bean, that I passed in the view, via a model which I added in my controller, e.g.:

${myBean.doSomething()
// or
${myBean.doSomething(parameters)

If this is not understandable I can update my question with some code (I believe that Spring developers understand what I am talking about).

I don't know how to pass this expression. What attribute of button or link tag to use? I used "action" attribute for the button:

<input type="button" th:action="${myBean.doSomething()".../>

or "href" attribute in the link tag:

<a th:href= "${myBean.getStringUrlAndDoSomething()"/>

Very significant info

When I started my tomcat running the page, the actions in the EL are run successfuly on the load of the page. When I pressed the button or the link nothing happened.

I know that I cannot use "onclick" attribute because there we write JS code. But I need to run Java Spring code.

Any ideas about solving my problem? Thanks in advance


Solution

  • I followed the advice of the @M.Deinum, @Wim Deblauwe, and I did not use a button for this job. Button needs a form to work.

    That is why I used a link, where the method from the bean is called like a charm, like the following snippet:

    <div class="blabla">
        <div class="blablabla" th:text="|#{change_lang} EN/GR:|"></div>
        <a class="bla" th:href="${localeService.switchLocale()}">
            <div th:class="|${localeService.loadCss()}_blabla|"></div>
        </a>
        <span th:text="${#locale.getLanguage()}"></span>
    </div>
    

    And next is a snippet from the bean:

    public String switchLocale() {
    
            locale = LocaleContextHolder.getLocale();
    
            if (locale.getLanguage().equals("en")) {
                LocaleContextHolder.setLocale(EN_LOCALE);
                return "?lang=el";
            } else if (locale.getLanguage().equals("el")) {
                LocaleContextHolder.setLocale(GR_LOCALE);
                return "?lang=en";
            } else {
                return "";
            }
        }
    

    So, the code from the bean IS invoked successfuly. I guess this is the solution to my issue.

    Thanks a lot from the 2 people @M.Deinum, @Wim Deblauwe, who advised me.