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

1k views Asked by At

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.

2

There are 2 answers

1
amphibient On BEST ANSWER

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.

1
Roman C On

You can get action bean from action invocation like you do in the interceptor or from the value stack where it's already pushed. Since you have access to the value stack from JSP and know how to print property the easiest way for you to set the action bean to the request attribute with <s:set> tag.

<s:set var="action" value="action" scope="request"/> 

Now you can get the action bean

<% 
  MyAction myActionBean = request.getAttribute("action");
  String someVal = myActionBean.getSomeValue();
  System.out.println(someVal);
%>