`
robin35java
  • 浏览: 20462 次
  • 性别: Icon_minigender_2
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Struts 2.0的Action讲解

阅读更多
http://www.35java.com/zhibo/forum.php?mod=viewthread&tid=374&extra=page%3D3
有Struts 1.x经验的朋友都知道Action是Struts的核心内容,当然Struts 2.0也不例外。不过,Struts 1.x与Struts 2.0的Action模型很大的区别。
                                                 Struts 1.x Stuts 2.0
接口 必须继承org.apache.struts.action.Action或者其子类 无须继承任何类型或实现任何接口
表单数据 表单数据封装在FormBean中 表单数据包含在Action中,通过Getter和Setter获取
                                虽然,理论上Struts 2.0的Action无须实现任何接口或继承任何类型,但是,我们为了方便实现Action,大多数情况下都会继承com.opensymphony.xwork2.ActionSupport类,并重载(Override)此类里的String execute()方法。具体的实现,如例1所示:
                                                <%                                @ page contentType                                =                                "                                text/html; charset=UTF-8                                "                               
                                %>                               
                                <%                                @ taglib prefix                                =                                "                                s                                "                                uri                                =                                "                                /struts-tags                                "                               
                                %>                               
                                <                                html                                >                               
                                <                                head                                >                               
                                <                                title                                >                                Hello World!                                </                                title                                >                               
                                </                                head                                >                               
                                <                                body                                >                               
                                <                                h2                                ><                                s:property                                 value                                ="message"                                /></                                h2                                >                               
                                </                                body                                >                               
                                </                                html                                >               
                例1 HelloWorld.jsp               
               
                                                                                package                                tutorial;

                                import                                java.text.DateFormat;
                                import                                java.util.Date;

                                import                                com.opensymphony.xwork2.ActionSupport;

                                public                               
                                class                                HelloWorld                                 extends                                ActionSupport                                                                                                                                                                                                 {
                                                    private                                                String message;
   
                                                    public                                                String getMessage()                                                                                                                                                                                                                                                                                 {
                                                                        return                                                                message;
    }                                                                                                                                                               
                                                                   
    @Override
                                                    public                                                String execute()                                                                                                                                                                                                                                                                                 {
        message                                                                 =                                                               
                                                                "                                                                Hello World, Now is                                                                 "                                                               
                                                                +                                                                DateFormat.getInstance().format(                                                                new                                                                Date());
                                                                        return                                                                SUCCESS;
    }                                                                                                                                                               
                                                                }                                               
                例1 classes/tutorial/HelloWorld.java               
               
                                                <                                package                                 name                                ="ActionDemo"                                extends                                ="struts-default"                                >                               
                                <                                action                                 name                                ="HelloWorld"                                class                                ="tutorial.HelloWorld"                                >                               
                                <                                result                                >                                /HelloWorld.jsp                                </                                result                                >                               
                                </                                action                                >                               
                                </                                package                                >               
                例1 classes/struts.xml中HelloWorld Action的配置               
               
                在浏览器地址栏中键入http://localhost:8080/Struts2_Action/HelloWorld.action,可以看到如图1所示页面。
                               
                图1 HelloWorld输出页面               
               
参考JavaDoc,可知ActionSupport类实现了接口:
com.opensymphony.xwork2.Action
com.opensymphony.xwork2.LoaleProvider
com.opensymphony.xwork2.TextProvider
com.opensymphony.xwork2.Validateable
com.opensymphony.xwork2.ValidationAware
com.uwyn.rife.continuations.ContinuableObject
java.io.Searializable
java.lang.Cloneable

默认情况下,当请求HelloWorld.action发生时,Struts运行时(Runtime)根据struts.xml里的Action映射集(Mapping),实例化tutoiral.HelloWorld类,并调用其execute方法。当然,我们可以通过以下两种方法改变这种默认调用。这个功能(Feature)有点类似Struts 1.x中的LookupDispathAction。

在classes/sturts.xml中新建Action,并指明其调用的方法;
访问Action时,在Action名后加上“!xxx”(xxx为方法名)。

实现方法请参考例2:
在classes/tutorial/HelloWorld.java中加入以下方法:
public String aliasAction() {
    message =
"自定义Action调用方法";
    return SUCCESS;
}
例2 classes/tutorial/HelloWorld.java代码片段

实现方法一,在classes/sturts.xml中加入下面代码:
<action name="AliasHelloWorld" class="tutorial.HelloWorld" method="aliasAction">
<result>/HelloWorld.jsp</result>
</action>
例2 classes/struts.xml中AlaisHelloWorld Action的配置

实现方法二,使用http://localhost:8080/Struts2_Action/HelloWorld!aliasAction.action地址来访问HelloWorld Action。 在浏览器地址栏中键入http://localhost:8080/Struts2_Action/AliasHelloWorld.action或 http://localhost:8080/Struts2_Action/HelloWorld!aliasAction.action,可以看到如图2所示页面。

图2 自定义Action调用方法页面通过上面的两个例子,细心的朋友应该可能会发现classes/tutorial/HelloWorld.java中Action方法(execute和aliasAction)返回都是SUCCESS。这个属性变量我并没有定义,所以大家应该会猜到它在ActionSupport或其父类中定义。没错,SUCCESS在接口com.opensymphony.xwork2.Action中定义,另外同时定义的还有ERROR, INPUT, LOGIN, NONE。
此外,我在配置Action时都没有为result定义名字(name),所以它们默认都为success。值得一提的是Struts 2.0中的result不仅仅是Struts 1.x中forward的别名,它可以实现除forward外的很激动人心的功能,如将Action输出到FreeMaker模板、Velocity模板、JasperReports和使用XSL转换等。这些都过result里的type(类型)属性(Attribute)定义的。另外,您还可以自定义result类型。
下面让我们来做一个Velocity模板输出的例子,首先在classes/struts.xml中新建一个Action映射(Mapping),将其result类型设为velocity,如以下代码所示:
<action name="VMHelloWorld" class="tutorial.HelloWorld">
<result type="velocity">/HelloWorld.vm</result>
</action>
例3 classes/struts.xml中VMHelloWorld Action的配置

新建HelloWorld.vm,内容如下所示:
<html>
<head>
<title>Velocity</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>Message rendered in Velocity: $message</h2>
</body>
</html>
例3 HelloWorld.vm
在浏览器地址栏中键入http://localhost:8080/Struts2_Action/VMHelloWorld.action,页面输出如下图3所示。

图3 HelloWorld.vm的输出页面 要运行例3需要在WEB-INF/lib中添加以下几个包:
commons-collections-3.2.jar
velocity-1.4.jar
velocity-tools-view-1.2.jar
avalon-logkit-2.1.jar


前面,我花了不少的时间讨论Action的输出。我老板有句名言——程序无非就是输入、操作和输出。因此,现在我们要讨论一下输入——表单输入。
使用Struts 2.0,表单数据的输入将变得非常方便,和普通的POJO一样在Action编写Getter和Setter,然后在JSP的UI标志的name与其对应,在提交表单到Action时,我们就可以取得其值。
让我们看一个例子,新建Login Action,它通过Login.jsp的表单获得用户名和密码,验查用户名是否为“max”,密码是否则为“secret”。如果,两者都符合,就在HelloWorld中显示“Welcome, max”,否则显示“Invalid user or Password”。
package tutorial;

import com.opensymphony.xwork2.ActionSupport;

public
class Login extends ActionSupport {
    private String name;
    private String password;
    private String message;
   
    public String getName() {
        return name;
    }
   
    public
void setName(String name) {
        this.name = name;
    }
   
    public String getPassword() {
        return password;
    }
   
    public
void setPassword(String password) {
        this.password = password;
    }
   
    public String getMessage() {
        return message;
    }

    @Override
    public String execute() {
        if("max".equals(name) &&
"Secret".equals(password)) {
            message =
"Welcome, "
+ name;
        }
else
{
            message =
"Invalid user or password";
        }
        return SUCCESS;
    }
}
例4 classes/tutorial/Login.java

<%@ page contentType="text/html; charset=UTF-8"
%>
<%@ taglib prefix="s" uri="/struts-tags"
%>
<html>
<head>
<title>Login</title>
</head>
<body>
<s:form action="Login" method="POST">
<s:textfield name="name" label="User name"
/>
<s:password name="password" label="Password"
/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
例4 Login.jsp

<action name="Login" class="tutorial.Login">
<result>/HelloWorld.jsp</result>
</action>
例4 classes/struts.xml中Login Action的配置

运行Tomcat,在浏览器地址栏中键入http://localhost:8080/Struts2_Action/Login.jsp,出现如图4所示页面。


图4 Login.jsp输出页面

分别在User name中输入“max”和“secret”,点击“Submit”按钮,出现如图5所示页面。



图5 Login成功页面

在浏览器地址栏中键入http://localhost:8080/Struts2_Action/Login.jsp,分别在User name中输入“Scott”和“password”,点击“Submit”按钮,出现如图6所示页面。


图6 Login失败页面  Struts 2.0更厉害的是支持更高级的POJO访问,如user.getPassword()。我们可以用另一写法实现例4。首先,将name和password从Login类中分离出来,到新建类User中。这样对我们开发多层系统尤其有用。它可以使系统结构更清晰。
package tutorial;

import com.opensymphony.xwork2.ActionSupport;

public
class LoginX extends ActionSupport {
    private User user;
    private String message;
   
    public
void setUser(User user) {
        this.user = user;
    }
   
    public User getUser() {
        return user;
    }
   
    public String getMessage() {
        return message;
    }
   
    @Override
    public String execute() {       
        if("max".equals(user.getName()) &&
"secret".equals(user.getPassword())) {
            message =
"Welcome, "
+ user.getName();
        }
else
{
            message =
"Invalid user or password";
        }
        return SUCCESS;
    }
}
例5 classes/tutorial/LoginX.java

<%@ page contentType="text/html; charset=UTF-8"
%>
<%@ taglib prefix="s" uri="/struts-tags"
%>
<html>
<head>
<title>Login</title>
</head>
<body>
<s:form action="LoginX" method="POST">
<s:textfield name="user.name" label="User name"
/>
<s:password name="user.password" label="Password"
/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
例5 LoginX.jsp

<action name="LoginX" class="tutorial.LoginX">
<result>/HelloWorld.jsp</result>
</action>
例5 classes/struts.xml中的LoginX Action配置  很多时候我的同事会问我:“如果我要取得Servlet API中的一些对象,如request、response或session等,应该怎么做?这里的execute不像Struts 1.x的那样在参数中引入。”开发Web应用程序当然免不了跟这些对象打交道。在Strutx 2.0你可以有两种方式获得这些对象:非IoC(控制反转Inversion of Control)方式和IoC方式。

非IoC方式
要获得上述对象,关键Struts 2.0中com.opensymphony.xwork2.ActionContext类。我们可以通过它的静态方法getContext()获取当前Action的上下文对象。 另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象。


HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();

如果你只是想访问session的属性(Attribute),你也可以通过ActionContext.getContext().getSession()获取或添加session范围(Scoped)的对象。
IoC方式
要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。具体实现,请参考例6 IocServlet.java。

package tutorial;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public
class NonIoCServlet extends ActionSupport {
    private String message;
   
    public String getMessage() {
        return message;       
    }
   
    @Override
    public String execute() {   
        ActionContext.getContext().getSession().put("msg", "Hello World from Session!");
       
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();       
        HttpSession session = request.getSession();
       
        StringBuffer sb =
new StringBuffer("Message from request: ");
        sb.append(request.getParameter("msg"));
        sb.append("<br>Response Buffer Size: ");
        sb.append(response.getBufferSize());
        sb.append("<br>Session ID: ");
        sb.append(session.getId());
       
        message = sb.toString();
        return SUCCESS;
    }
}
例6 classes/tutorial/NonIoCServlet.java

package tutorial;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public
class IoCServlet extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {
    private String message;
    private Map att;
    private HttpServletRequest request;
    private HttpServletResponse response;   
   
    public String getMessage() {
        return message;       
    }
   
    public
void setSession(Map att) {
        this.att = att;
    }
   
    public
void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
   
    public
void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
   
    @Override
    public String execute() {       
        att.put("msg", "Hello World from Session!");
       
        HttpSession session = request.getSession();
       
        StringBuffer sb =
new StringBuffer("Message from request: ");
        sb.append(request.getParameter("msg"));
        sb.append("<br>Response Buffer Size: ");
        sb.append(response.getBufferSize());
        sb.append("<br>Session ID: ");
        sb.append(session.getId());
       
        message = sb.toString();
        return SUCCESS;
    }
}
例6 classes/tutorial/IoCServlet.java

<%@ page contentType="text/html; charset=UTF-8"
%>
<%@ taglib prefix="s" uri="/struts-tags"
%>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h2>
<s:property value="message" escape="false"/>
<br>Message from session: <s:property value="#session.msg"
/>
</h2>
</body>
</html>
例6 Servlet.jsp

<action name="NonIoCServlet" class="tutorial.NonIoCServlet">
<result>/Servlet.jsp</result>
</action>
<action name="IoCServlet" class="tutorial.IoCServlet">
<result>/Servlet.jsp</result>
</action>
例6 classes/struts.xml中NonIocServlet和IoCServlet Action的配置运行Tomcat,在浏览器地址栏中键入http://localhost:8080/Struts2_Action/NonIoCServlet.action?msg=Hello%20World! 或http://localhost:8080/Struts2_Action/IoCServlet.action?msg=Hello%20World!,出现如图7所示页面。


图7 Servlet.jsp的输出页面
分享到:
评论

相关推荐

    struts2.0中文教程

    03 Struts 2.0的Action讲解 04 在Struts 2.0中国际化(i18n)您的应用程序 05 转换器(Converter)——Struts 2.0中的魔术师 06 在Struts 2.0中实现表单数据校验(Validation) 07 Struts 2的基石——拦截器...

    Struts 2.0系列(MAX)

    Struts 2.0的Action讲解 在Struts 2.0中国际化(i18n)您的应用程序 转换器(Converter)——Struts 2.0中的魔术师 在Struts 2.0中实现表单数据校验(Validation) Struts 2的基石——拦截器(Interceptor) 在...

    Struts2.0视频教程+struts2.0中文教程

    Struts2.0是Java Web开发中的一个强大框架,它基于Model-View-Controller(MVC)设计模式,为开发者提供了构建可维护性高、结构清晰的Web应用程序的工具。这个"Struts2.0视频教程+struts2.0中文教程"包含的资源旨在...

    struts 2.0 详细讲解 4个PPT

    本详细讲解将涵盖四个关键主题:拦截器、标签、配置详解以及Struts 2.0的基础知识。 **1. Struts 2.0 拦截器** 拦截器是Struts 2的核心特性之一,它们类似于AOP(面向切面编程)的概念,可以实现在动作执行前后插入...

    Struts 2.0全攻略之Struts 2.0参考手册

    下面,我们将详细讲解Struts 2.0的关键知识点。 1. **Struts 2.0架构** Struts 2.0基于Model-View-Controller(MVC)设计模式,提供了一种解耦应用程序逻辑、视图和控制的结构。它采用了拦截器模型来处理请求,...

Global site tag (gtag.js) - Google Analytics