Search code examples
javajspstruts2ognlvaluestack

Access to controller methods in JSP Java scriptlet rather than using tags?


My struts configuration:

<action name="myAction" class="my.controller.MyAction">
    <result name="myPage">/myPage.jsp</result>

MyAction has a method public String getSomeValue() { ... }.

In myPage.jsp, I can print that value easily to the HTML stream:

<s:property value="someValue" />

However, I would like to print it to the console:

<%

//how do I reference myActionBean
String someVal = myActionBean.getSomeValue();
System.out.println(someVal);

%>

My question is, how do I reference the action controller (replace myActionBean in the code above) inside a JSP code block, just like the s:property tag does in its syntax that eliminates the "get" part of the method ? I would like to access myActionBean.getSomeValue() in Java in the JSP rather than doing it in a tag. I know this is not a recommended way of doing things but this is just for debugging.


Solution

  • As suggested by @DaveNewton, I was able to access the action class from the context:

    <%
        ActionContext context = ActionContext.getContext();
    
        //this will access actionClass.getFoo() just like the tag
        //<s:property value="%{foo}"/> does but outputs to HTML
        Object fooObj = context.getValueStack().findValue("foo");
        String fooStr = (String)fooObj;
    
        //so that we can print it to the console
        //because the tag can only output to HTML 
        //and printing to the console is the objective of the question
        System.out.println("foo = " + fooStr);
    %>
    

    I had to import ActionContext on top of the JSP:

    <%@ page import="com.opensymphony.xwork2.ActionContext" %>
    

    I understand some folks don't like that I should want to do this but that is actually exactly what I wanted to do. I know well that I could do a System.out in getFoo() itself but I wanted to do it in the JSP.