一、Struts 2 基础---4.Struts 2中的Action

来源:互联网 发布:聚划算自动抢购软件 编辑:程序博客网 时间:2024/06/03 05:31
 Struts 2Action

       Action中包含了对用户请求的处理逻辑。

1.  实现Action实现类

Struts 2 中的Action可以是一普通的POJO。其execute可以是无参数的。

1.1

 

public class LoginAction {

       private String username;

       private String password;

       private String Tip;

public String getPassword() {

              return password;

       }

       public void setPassword(String password) {

              this.password = password;

       }

       public String getUsername() {

        return username;

}

public void setUsername(String username) {

        this.username = username;

}

public String getTip() {

        return Tip;

}

       public void setTip(String tip) {

        Tip = tip;

}    

       public String execute() throws Exception {

        return “success”

}

}

 

注意:LoginActionexecute()方法不带有任何参数。而在Struts中是有ActionMapppingActionFormHttpServletRequestHttpServletResponse等参数的。

        LoginAction返回的参数是个普通的String。而在Struts中返回参数是个ActionForward

        Struts2中的Action之所以如此简单正式因为Struts2中运用了AOP的思想,用拦截器对输入的参数的返回的参数进行处理。从而实现了和servlet 的解耦。

        同样由于Struts2返回的是个普通的String。也就是说只是一个名字。所以可以很容易的把它映射到不同的处理模板中。

 

        为方便用户的使用,Strut 2也提供了一个Action接口和一个ActionSupport实现类。

        Action接口中主要定义了返回名称的规范。

 

Action接口定义如下:

public interface Action {

        public static final String ERROR = “error”;

        public static final String INPUT = “input”;

        public static final String LOGIN =”login”;

        public static final String NONE = “none”;

        public static final String SUCCESS = “success”;

 

        public String execute() throws Exception;

}

 

ActionSupportAction接口的实现类,它在Action的基础上增加了输入校验、获取国际化信息等方法。ActionSupportStruts2的默认Action处理类。它的主要方法如下:

 

package com.opensymphony.xwork2;

 

public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {

        ……

 

    public void setActionErrors(Collection errorMessages) {

        validationAware.setActionErrors(errorMessages);

    }

 

    public Collection getActionErrors() {

        return validationAware.getActionErrors();

    }

 

    public void setActionMessages(Collection messages) {

        validationAware.setActionMessages(messages);

    }

 

    public Collection getActionMessages() {

        return validationAware.getActionMessages();

    }

 

    /**

     * @deprecated Use {@link #getActionErrors()}.

     */

    public Collection getErrorMessages() {

        return getActionErrors();

    }

 

    /**

     * @deprecated Use {@link #getFieldErrors()}.

     */

    public Map getErrors() {

        return getFieldErrors();

    }

 

    public void setFieldErrors(Map errorMap) {

        validationAware.setFieldErrors(errorMap);

    }

 

    public Map getFieldErrors() {

        return validationAware.getFieldErrors();

    }

 

    public Locale getLocale() {

        ActionContext ctx = ActionContext.getContext();

        if (ctx != null) {

            return ctx.getLocale();

        } else {

            LOG.debug("Action context not initialized");

            return null;

        }

    }

 

    public String getText(String aTextName) {

        return textProvider.getText(aTextName);

    }

 

    public String getText(String aTextName, String defaultValue) {

        return textProvider.getText(aTextName, defaultValue);

    }

 

    public String getText(String aTextName, String defaultValue, String obj) {

        return textProvider.getText(aTextName, defaultValue, obj);

    }

 

    public String getText(String aTextName, List args) {

        return textProvider.getText(aTextName, args);

    }

 

    ……

 

    public ResourceBundle getTexts() {

        return textProvider.getTexts();

    }

 

    public ResourceBundle getTexts(String aBundleName) {

        return textProvider.getTexts(aBundleName);

    }

 

    public void addActionError(String anErrorMessage) {

        validationAware.addActionError(anErrorMessage);

    }

 

    public void addActionMessage(String aMessage) {

        validationAware.addActionMessage(aMessage);

    }

 

    public void addFieldError(String fieldName, String errorMessage) {

        validationAware.addFieldError(fieldName, errorMessage);

    }

 

    public String input() throws Exception {

        return INPUT;

    }

   

    public String doDefault() throws Exception {

        return SUCCESS;

    }

 

    /**

     * A default implementation that does nothing an returns "success".

     * <p/>

     * Subclasses should override this method to provide their business logic.

     * <p/>

     * See also {@link com.opensymphony.xwork2.Action#execute()}.

     *

     * @return returns {@link #SUCCESS}

     * @throws Exception  can be thrown by subclasses.

     */

    public String execute() throws Exception {

        return SUCCESS;

    }

 

    public boolean hasActionErrors() {

        return validationAware.hasActionErrors();

    }

 

    public boolean hasActionMessages() {

        return validationAware.hasActionMessages();

    }

 

    public boolean hasErrors() {

        return validationAware.hasErrors();

    }

 

    public boolean hasFieldErrors() {

        return validationAware.hasFieldErrors();

    }

 

    /**

     * Clears field errors. Useful for Continuations and other situations

     * where you might want to clear parts of the state on the same action.

     */

    public void clearFieldErrors() {

        validationAware.clearFieldErrors();

    }

 

    /**

     * Clears action errors. Useful for Continuations and other situations

     * where you might want to clear parts of the state on the same action.

     */

    public void clearActionErrors() {

        validationAware.clearActionErrors();

    }

 

    /**

     * Clears messages. Useful for Continuations and other situations

     * where you might want to clear parts of the state on the same action.

     */

    public void clearMessages() {

        validationAware.clearMessages();

    }

 

    /**

     * Clears all errors. Useful for Continuations and other situations

     * where you might want to clear parts of the state on the same action.

     */

    public void clearErrors() {

        validationAware.clearErrors();

    }

 

    /**

     * Clears all errors and messages. Useful for Continuations and other situations

     * where you might want to clear parts of the state on the same action.

     */

    public void clearErrorsAndMessages() {

        validationAware.clearErrorsAndMessages();

    }

 

    /**

     * A default implementation that validates nothing.

     * Subclasses should override this method to provide validations.

     */

    public void validate() {

    }

 

    public Object clone() throws CloneNotSupportedException {

        return super.clone();

    }

 

    ……

 

}

 

2.  Action访问Servlet API

前面提到Struts2中的Action没有直接和Servlet API耦合,但有时Web应用中需要访问HttpServletRequestHttpSessionServletContext。所以Struts2中提供了ActionContext类对上述类的对象进行访问。

 

2.1

LoginActionexecute方法:

public String execute() throws Exception {

       ActionContext.ctx = ActionContext.getContext();

       Integer counter = (Integer)ctx.getApplication().get("counter");

        if(counter == null){

           counter=1;

       } else {

           counter = counter + 1;

       }

       ctx.getApplication().put("counter", counter);

       ctx.getSession().put("user", getUsername());

       if(getUsername().equals("scott") && getPassword().equals("tiger")){

           ctx.put("tip", "服务器提示:您已成功的登录");

           return SUCCESS;

       } else {

           ctx.put("tip", "服务器提示:登录失败");

           return ERROR;

       }

}

 

struts.xml:

<struts>

    <package name="lee" extends="struts-default">

        <action name="*_*Action" class="lee.{2}Action" method="{1}">

             <result name="input">/login.jsp</result>

            <result name="error">/error.jsp</result>

            <result name="welcome">/welcome.jsp</result>

        </action>

    </package>

</struts>

 

welcome.jsp:

<%@ page language="java" contentType="text/html; charset=GBK"%>

<html>

    <head>

        <title>成功页面</title>

    </head>

    <body>

       本站访问次数为:${applicationScope.counter}<br>

        ${sessionScope.user},您已经登录!<br>

       ${requestScope.tip}

    </body>

</html>

 

3. Action中直接访问Servlet API

Struts 2 提供如下接来直接访问Servlet API

l         ServletContextAware:实现该接口的Action可以直接访问HttpContextAware实例。

l         ServletRequestAware: 实现该接口的Action可以直接访问HttpServletRequest实例。

l         ServletResponseAware: 实现该接口的Action可以直接访问HttpServletResponse实例。

 

3.1

 

    public String execute() throws Exception{

       Cookie c = new Cookie("user" , getUsername());

       c.setMaxAge(60 * 60);

       response.addCookie(c);

       return SUCCESS;

 

}

 

Struts 2中还提供了ServletActionContext方法来访问Servlet API

 

4. Action的配置

Struts.xmlAction配置的一般形式如下:

<package>

    <action name=”...” class=”...”>

       <result .../>

       <result .../>

    </action>

    ...

</package>

 

[] 如果不指定class属性则默认使用系统得ActionSupport类。

 

result元素的内容后面讲。

 

5. 动态方法调用

Struts1框架提供了DispatchAction,从而允许一个Action内包含多个处理逻辑。类似的在Struts2也可以在一个Action中对应多个请求的处理。我们只需在Action中写好相应得方法。然后在struts.xml完成配置即可。

5.1

public class LoginRegistAction extends ActionSupport {

    ...

    public String regist() throws Exception {

    ...

    return SUCCESS;

    }

 

    public String execute() throws Excetion {

    ...

    Return SUCCESS;

    }

}

 

struts.xml:

...

<action name=”Login” class=”lee.LoginRegistAction”/>

 

<action name=”Regist” class=”lee.LoginRegistAction” method=”regist”/>           --------------------

...

</action>

 

可见只需在struts.xml中配置method属性就可以指定相应方法处理用户请求了。如不配置method元素,则将使用execute方法处理用户请求。

 

[]上例中客户端是通过“Regist.action”提交请求,从映射到regist方法的。

    如果struts.xml中只指定了Action的映射,即去掉。那么客户端仍然可以通过“Login!regist.action”的方式来指定regist方法处理请求。

 

6. 使用通配符

在配置Action时可以使用通配符来实现各种灵活的配置,通过一个例子说明:

 

有如下配置:

    ...

    <action name=”*_*” class=”action.{1}” method=”{2}”>

       <result>/{1}.jsp</result>

    ...

则当提交请求为User_login.action时,将提交action.User类的login方法处理。处理成功后转到User.jsp文件。

 

 

匹配的优先级:

    如有三个Action的配置*Action*LoginAction,当提交LoginAction.action时匹配那个?提交abcAction.action又该匹配那个?

 

匹配法则:  先找和URL完全匹配的Action(没有通配符的),如果找到则匹配。如果找不到则按顺序和使用通配符的Action匹配。由最先匹配成功的Acion处理用户请求。

 

原创粉丝点击