前面介绍的所有action文件中,都有方法public String execute(){},其实这不是唯一的写法,execute这个单词是可以改变的,在struts.xml文件中,execute方法是作为默认方法执行的,我们只要在struts.xml文件中做一些手脚就可以解决。
1.新建一个showMessage.java类:
package controller; import java.util.ArrayList; import com.opensymphony.xwork2.ActionSupport; public class showMessage extends ActionSupport{ private ArrayList<String> nameList = new ArrayList<String>(); private ArrayList<String> bookList = new ArrayList<String>(); private ArrayList<Integer> ageList = new ArrayList<Integer>(); public String showName() throws Exception { nameList.add("niu"); nameList.add("jia"); nameList.add("bin"); return "showname"; } public String showAge() throws Exception { ageList.add(11); ageList.add(12); ageList.add(13); return "showage"; } public String showBook() throws Exception { bookList.add("sf"); bookList.add("cg"); bookList.add("st"); return "showbook"; } }
唯一与execute不同的地方在于,分别定义了三个方法showBook,showAge,showName。
2.新建show.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s" %> <body> <a href="showName.action">showName</a> <br> <a href="showAge.action">showAge</a> <br> <a href="showBook.action">showBook</a> <br> </body> </html>
3.struts.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtd/struts-2.0.dtd"> <struts> <package name="Maybe" extends="struts-default"> <action name="showBook" class="controller.List" method="showBook"> <result name="showbook">/showbook.jsp</result> </action> <action name="showAge" class="controller.List" method="showAge"> <result name="showage">/showage.jsp</result> </action> <action name="showName" class="controller.List" method="showname"> <result name="showname">/showname.jsp</result> </action> </package> </struts>
4.新建showbook.jsp,showage.jsp,showname.jsp
以showname.jsp为例:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s" %> <body> <s:iterator value="nameList" var="namelist"> <s:property value="namelist"/> <br> </s:iterator> </body> </html>
5:运行show.jsp->点击showName:
6.全局result:
以上result name只对当前路径有效,如果改成以下形式,则对全局都有效:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtd/struts-2.0.dtd"> <struts> <package name="Maybe" extends="struts-default"> <global-results> <result name="showage">/showage.jsp</result> <result name="showbook">/showbook.jsp</result> <result name="showname">/showname.jsp</result> </global-results> <action name="showBook" class="controller.showMessage" method="showBook"> </action> <action name="showAge" class="controller.showMessage" method="showAge"> </action> <action name="showName" class="controller.showMessage" method="showName"> </action> </package> </struts>
如果局部和全局result名称相同,局部的优先级要比全局的优先级要高,大家可以自己验证一下。