(Struts2学习系列三)Struts2动态方法调用:通配符方式

时间:2022-09-18 10:15:32

  更改src/struts2.xml的代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="*_*" method="{2}" class="action.{1}Action">
<result>/result.jsp</result>
<result name="add">/{2}.jsp</result>
<result name="update">/{2}.jsp</result>
</action>
</package>
</struts>

  {1},{2}表示*的顺序,{1}是"_"前面的*,{2}是"_“后面的*.

  HelloWorldAction.java的add和update方法也要修改返回值:

public class HelloWorldAction extends ActionSupport{

    public String add(){
return "add";
} public String update(){
return "update";
} @Override
public String execute() throws Exception{
// TODO Auto-generated method stub
System.out.println("执行Action");
return "success";
} }

  启动tomcat,然后就可以访问

  http://localhost:8080/struts2Test2/HelloWorld.action或者http://localhost:8080/struts2Test2/HelloWorld_.action

  http://localhost:8080/struts2Test2/HelloWorld_add.action

  http://localhost:8080/struts2Test2/HelloWorld_update.action