访问Action时默认调用execute()
可以在Action中定义多个业务方法(如下格式):
public String XXX(){
return "";
}
配置多个<action>标签,通过设置method属性,来进行对应。
多个业务方法配置一个action(可以通过通配符实现),其中方法中的方法名与返回值相同。
<action name="*" class="..." method="{1}">
<result name="{1}">...</result>
</action>
动态方法调用(功能类似设置method属性):
DMI(dynamic method invocation)
使用动态调用之前,首先需要设置启用动态调用。
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
使用动态调用时,在struts.xml中无需设置method属性:
<action name="house" class=".." >
<result>/index.jsp</result>
</action>
通过uri调用对应的action方法,如:
http://localhost:8080/house!(方法名)
Struts2
配置详解
result的类型(type) 默认是dispatcher
可以于struts-default.xml文件中查看类型
1)dispatcher:org.apache.struts2.dispatcher.ServletDispatcherResult默认结果类型,用来呈现JSP页面
2)chain: com.opensymphony.xwork2.ActionChainResult将action和另外一个action链接起来
3)freemarker: org.apache.struts2.views.freemarker.FreemarkerResult呈现Freemarker模板
4)httpheader: org.apache.struts2.dispatcher.HttpHeaderResult返回一个已配置好的HTTP头信息响应
5)redirect: org.apache.struts2.dispatcher.ServletRedirectResult将用户重定向到一个已配置好的URL
6)redirectAction: org.apache.struts2.dispatcher.ServletActionRedirectResult将用户重定向到一个已定义好的action
7)stream: org.apache.struts2.dispatcher.StreamResult将原始数据作为流传递回浏览器端,该结果类型对下载的内容和图片非常有用
8)velocity: org.apache.struts2.dispatcher.VelocityResult呈现Velocity模板
9)xslt: org.apache.struts2.views.xslt.XSLTResult呈现XML到浏览器,该XML可以通过XSL模板进行转换
10)plaintext : org.apache.struts2.dispatcher.PlainTextResult返回普通文本类容
实现全局结果的效果:
1)在每个<action>>内加<result>
2)全局结果,使用<global-results> 且需置于所有的<action>之前。
<global-results>
<result name="success">..</result>
</global-results>
设置全局异常结果:
<global-results
<result name="add">/add.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping name="" exception="..." />
<result name="error">/index.jsp</result>
</global-exception-mapping>
动态结果 EL表达式(使用动态结果时,在相应Action中设置对应属性的getXXX和setXXX方法):
<!-- 动态结果 -->
<action name="log2" class="com.hlx.action2.LoginAction" method="log2">
<result name="success">${result}</result>
</action>
namespace 命名空间,访问时需要加上命名空间,当取值为“”或者不配置时,不管路径有多深,只需action匹配,即可访问:
http://localhost:8080/p1/p2/p3/login
Struts2访问顺序:p3->p2->p1->根目录
在struts.xml中可以通过include导入struts配置xml文件,如:
<struts>
...
<include file="struts-house.xml"/>
...
</struts>
Servlet API类型:
HttpServletRequest request
HttpSession session
ServletContext application
Struts2中传统Servlet API类型被处理成Map类型,不依赖传统Servlet API ——松耦合
一、保存数据
1)Session
Map<String,Object> session = ActionContext.getContext().getSession();
session.put("uname","mike");
2)Application object
Map<String ,Object> application = ActionContext.getContext().getApplication();
application.put("www", "http://baidu.com");
3)Request Object
Map<String, Object> request = (Map<String,Object>) ActionContext.getContext().get("request");
request.put("address","hz");
在页面中获取保存的数据方式:
<s:property value="#request.address"/>
二、也可以通过实现RequestAware、SessionAware、ApplicationAware接口来保存数据。