Struts2 - Is it possible to access a back end method of an Action in JSP?

Asked

Viewed 332 times

2

I’m using Struts2 to build a web application. I have a method in a class called BaseAction, where all other actions extend it, as written below:

public boolean isUserFullyLogged() {
    final Boolean isLogado = (Boolean) this.retrieveSessionAttribute(Constantes.LOGADO);
    return (isLogado != null) && isLogado.booleanValue();
}

I want to access this method in my JSP to show or not certain content and tried the syntax below for this:

  • <s:if test="#userFullyLogged">Conteúdo</s:if>
  • <s:if test="%{#userFullyLogged}">Conteúdo</s:if>
  • <s:if test="userFullyLogged">Conteúdo</s:if>
  • <s:if test="%{userFullyLogged}">Conteúdo</s:if>

But none of them worked and the method just isn’t called. Does anyone know where I’m wrong and what the correct syntax to call a method in the back-end?

  • Why not just check the attribute in the session directly? To avoid repeating the test on all pages (improving maintenance), you could create a custom tag whose content is only rendered when the user is logged in and another for when not logged in. A tag file would be very practical.

1 answer

1

The problem is that you are trying to access an attribute userFullyLogged, that doesn’t exist.

Your call should simply be.

<s:if test="%{isUserFullyLogged()}">Conteúdo</s:if>

You can try a little better at the performance by making the isLogate be an attribute and not a variable, doing as an example below.

private Boolean isLogado;

public boolean isUserFullyLogged() {
    if (this.isLogado == null) {
        this.isLogado = (Boolean) this.retrieveSessionAttribute(Constantes.LOGADO);
    }
    return this.isLogado.booleanValue();
}

This way you will make a single call to the retrieveSessionAttribute method and also a single cast and this value will be unique for each instance of Action that extends Basection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.