使用Struts2在JSP中访问Action类 [英] Accessing Action class in JSP using Struts2

查看:182
本文介绍了使用Struts2在JSP中访问Action类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何在使用Struts2时轻松访问JSP中的Action类?虽然我知道通常可以使用Struts标签和OGNL,但实际上我发现它们都令人困惑(显然是由于无知)而且坦率地说它更容易在JSP中维护Java(更不用说它更容易解释为新的众所周知的程序员Java)。

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

...这将在 BaseAction 由你自己的Action类扩展的类,所以你可以在JSP中说:

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

然而,这一切看起来都过于复杂,并假设 OgnlValueStack中的精确订单 - 必须有更好的方法,非?

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

非常感谢任何建议!

推荐答案

如果您不想使用struts2标签,同样有效的方法是使用JSTL标签。这些标签由struts2支持,我猜测大多数主要的Java Web框架。

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.

强烈建议您在使用任何Java Web Framework的典型业务编程中避免使用servlet / scriplets。

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"/>

或使用JSTL同样有效(有些人甚至会说更有效,因为视图不再依赖于struts2)

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}" />

很少有程序员(我会说没有经验丰富的struts2程序员)会发现这更难理解比

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.

这篇关于使用Struts2在JSP中访问Action类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆