繁体   English   中英

访问JSP Java scriptlet中的控制器方法而不是使用标签?

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

我的支柱配置:

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

MyAction有一个方法public String getSomeValue() { ... }

myPage.jsp ,我可以轻松地将该值打印到HTML流:

<s:property value="someValue" />

但是,我想将其打印到控制台:

<%

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

%>

我的问题是,如何在JSP代码块内引用动作控制器(在上面的代码中将myActionBean替换),就像s:property标记的语法中消除了方法的“获取”部分一样? 我想在JSP myActionBean.getSomeValue() Java访问myActionBean.getSomeValue()而不是在标记中进行操作。 我知道这不是建议的处理方式,但这仅用于调试。

如@DaveNewton所建议,我能够从上下文访问动作类:

<%
    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);
%>

我必须在JSP上导入ActionContext

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

我知道有些人不喜欢我应该这样做,但这实际上正是我想要做的。 我知道我可以在getFoo()本身中执行System.out ,但我想在JSP中进行。

您可以像在拦截器中一样从动作调用中获取动作bean,也可以从已经被推送的值堆栈中获取动作bean。 由于您可以从JSP访问值堆栈,并且知道如何打印属性,因此最简单的方法是使用<s:set>标记将操作bean设置为request属性。

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

现在您可以获得动作豆

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM