Accessing Action class in JSP using Struts2

11,279

Solution 1

If you don't want to use struts2 tags an equally valid approach is to use JSTL tags. These tags are supported by struts2 and I'm guessing most major java web frameworks.

It is strongly recommended that you avoid servlets/scriplets in typical business programming using any Java Web Framework.

You probably already know this but to get a property from the action just say:

<s:property value="myProperty"/>

Or equally valid using the JSTL (some here would even say more valid as the view no longer depends on struts2)

<c:out value="${myProperty}" />

There are few programmers (and I would stand to say no seasoned struts2 programmers) who would find this harder to understand than

<%
  MyAction action = (MyAction)BaseAction.getCurrentAction(request);
  String myValue = action.getMyValue();
%>

There are only a handful of tags required to generate a page, you need to get properties, iterate to produce tables/lists and that's about it. The time learning those few tags will save a great deal of time.

Solution 2

To follow up on Quaternion's answer, you can access any public method in your action class from OGNL tags or JSTL as he suggested.

You can also pass parameters to the action class through the tags:

public String getHello(String value){
    return "Hello " + value + "!";
}

Which is called on the JSP:

<s:property value="getHello('Russell')"/>

Which outputs:

Hello Russell!
Share:
11,279
Alex
Author by

Alex

Updated on June 04, 2022

Comments

  • Alex
    Alex almost 2 years

    Does anyone know how to easily access the Action class in a JSP when using Struts2? While I know it is often possible to use Struts tags and OGNL, I actually find them both to be confusing (clearly due to ignorance) and quite frankly find it easier to maintain Java in the JSP (not to mention it's easier to explain to new programmers as everyone knows Java).

    I have searched for a solutions for years, and the best solution I have found is to call a static method from a class, that looks like:

    public static BaseAction getCurrentAction(HttpServletRequest request) {
        OgnlValueStack ognlStack = (OgnlValueStack)request.getAttribute(org.apache.struts2.ServletActionContext.STRUTS_VALUESTACK_KEY);
        return (BaseAction)ognlStack.getRoot().get(0);
    }
    

    ...which would be in a BaseAction class extended by you own Action class, so that in your JSP you can say:

    <%
      MyAction action = (MyAction)BaseAction.getCurrentAction(request);
      String myValue = action.getMyValue();
    %>
    

    However this all seems overly complicated and it assumes a precise order in the OgnlValueStack - there must be a better way, non?

    Many thanks for any advice!