struts2 action 配置

设置Struts 2处理的请求后缀及Action调用
1、在struts2中默认处理的请求后缀为action,我们可以修改struts.xml 和struts.properties来修改默认的配置,在struts.xml中<struts>添加子接点<constant name=”struts.action.extension” value=”do” /> 或者是修改struts.properties文件 添加struts.action.extension = do这都是一样的效果
     注意:struts.xml 和struts.properties的都放在src下发布的时候会自动拷贝到WEB-INF/classes下
2、如何调用Action的方法 这是本章的重点

1) 如果在Action中只有一个 execute方法那么配置好后就会自动访问这个方法。如果方法名字不是execute 那么我们需要在struts.xml中的Action接点添加一个method属性为该方法签名,如下:

<action method=”hello” name=”helloAction” class=”com.struts2.chapter5.HelloAction”></action>

这样就会调用hello的方法!
2)这是一个控制器负责处理一个请求的方式,但这样就会造成很多的Action类,给维护带来困难。所以可以让一个 Action可以处理多个不同的请求。对于一个学生信息管理模块来说,通过一个Action处理学生信息的添、查、改、删(CRUD)请求,可以大大减少 Action的数量,有效降低维护成本。下面代码让我们可以使用通配符来操作

 public class StudentAction{

     public String insertStudent(){…} 

     public String updateStudent(){…} 

}

<action name=”*Student” class=”com.struts2.chapter5.StudentAction” method=”{1}”>

    <result name=”success”>/result.jsp</result>

</action>

仔细观察一下,发现name属性中有一个”*”号,这是一个通配符,说白了就是方法名称,此时method必须配置成method={1},才能找到对应的方法。现在,如果想调用insertStudent方法,则可以输入下面的URL进行访问:http://localhost:8081/Struts2Demo/ insertStudent.do,如果想调用updateStudent方法,则输入http://localhost:8081/Struts2Demo/updateStudent.do即可。格式如何定义,完全由程序员决定,”*”放在什么地方,也是可以自定义的。

3)对于上面的StudentAction我们还可以这样配置

<action name=”studentAction” class=”com.struts2.demo.StudentAction”>
   <result name=”success”>/result.jsp</result>
  </action>

调用Action的方法还可以通过”Action配置名!方法名.扩展名”

http://localhost:8081/Struts2Demo/studentAction!insertStudent.do

http://localhost:8081/Struts2Demo/studentAction!updateStudent.do


原文地址:https://www.cnblogs.com/lishoubin/p/3211279.html