4.Struts2中Action的三种访问方式

1.传统的访问方式-很少使用

通过<action>标签中的method属性,访问到action中的具体方法

具体实现:

  1.action代码

import com.opensymphony.xwork2.ActionSupport;

/**
 * action访问方式
 * 演示传统的配置方式
 * @author NEWHOM
 *
 */
public class CustomerAction extends ActionSupport {
    
    private static final long serialVersionUID = 1L;
    
    public String add(){
    
        System.out.println("添加Customer成功...");
        
        return NONE;
    }
    
    public String delete(){
        
        System.out.println("删除Customer成功...");
        
        return NONE;
    }

}

  2.配置文件代码

        <!-- 传统的配置方式 -->
        <action name="Customer_add" class="com.struts2.web.action3.CustomerAction" method="add"/>
        <action name="Customer_delete" class="com.struts2.web.action3.CustomerAction" method="delete"/>

  3.页面代码

    <h3>传统的配置方式</h3>
    <a href="${pageContext.request.contextPath }/Customer_add.action">添加Customer</a>
    <a href="${pageContext.request.contextPath }/Customer_delete.action">删除Customer</a>

2.通配符访问方式-经常使用

通配符的访问方式:(访问的路径和方法的名称必须要有某种联系.) 通配符就是 * 代表任意的字符  

  1.action代码

/**
 * action访问方式
 * 演示通配符的访问方式
 * @author NEWHOM
 *
 */
public class UserAction extends ActionSupport{

    private static final long serialVersionUID = 1L;
    
    public String add(){
        
        System.out.println("添加User成功...");
        
        return NONE;
    }
    
    public String delete(){
        
        System.out.println("删除User成功...");
        
        return NONE;
    }

}

  2.配置文件代码

        <!-- 通配符的访问方式 -->
        <action name="User_*" class="com.struts2.web.action3.UserAction" method="{1}"/>

  3.页面代码

    <h3>通配符的访问方式</h3>
    <a href="${pageContext.request.contextPath }/User_add.action">添加User</a>
    <a href="${pageContext.request.contextPath }/User_delete.action">删除User</a>

3.动态的访问方式-很少使用

如果想完成动态方法访问的方式,需要开启一个常量,struts.enable.DynamicMethodInvocation = false,把值设置成true
注意:不同的Struts2框架的版本,该常量的值不一定是true或者false,需要自己来看一下。如果是false,需要自己开启。
  1.action代码
/**
 * action访问方式
 * 演示动态的方式
 * @author NEWHOM
 *
 */
public class LinkManAction extends ActionSupport{

    private static final long serialVersionUID = 1L;
    
    public String add(){
        
        System.out.println("添加LinkMan成功...");
        
        return NONE;
    }
    
    public String delete(){
        
        System.out.println("删除LinkMan成功...");
        
        return NONE;
    }

}

  2.配置文件代码

    <!-- 开启动态访问的常量 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>

    <!-- 动态的访问方式 -->
    <action name="LinkMan" class="com.struts2.web.action3.LinkManAction"/>

  3.页面代码

    <h3>动态方法的访问方式</h3>
    <a href="${pageContext.request.contextPath }/LinkMan!add.action">添加LinkMan</a>
    <a href="${pageContext.request.contextPath }/LinkMan!delete.action">删除LinkMan</a>
原文地址:https://www.cnblogs.com/NEWHOM/p/6782986.html