Struts2中有时可能会需要使用一个Action来处理多个请求,来提高编码的效率和减少代码量。例如,在登录界面上的表单中可能会有登录和注册两个事件请求,有几种方式可以借鉴:
1.采用DMI动态调用方法。
该方法的主要思想是在一个 Action 类中实现多个方法,香港虚拟主机,然后每个 action 请求中表明要调用该类中的哪个方法。使用 actionname!method 方式调用。
(1)LoginAction 类代码如下:
View Code
1 package com.main.action; com.opensymphony.xwork2.ActionSupport;LoginAction extends ActionSupport { 6private String username; 7private String psd; String login(){10if (“lihui”.equals(username) && “xhh”.equals(psd)) {11return SUCCESS;12} else {13return ERROR;14 }15 } String regist(){18return “regist”;19 } setUsername(String username){22this.username = username;23 } String getUsername(){.username;27 } setPsd(String psd){30this.psd = psd;31 } String getPsd(){.psd;35 }36 }
(2)struts.xml 配置如下:
DOCTYPE struts PUBLIC 3 “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” /success.jsp/error.jsp/regist.jsp
(3)在jsp中的action请求代码如下:
regist(){];; 6 form.submit(); 7 }姓名:密码:
2.直接指定 Action 元素的 method 属性
使用这个方法就不必用 ! 将action和method连接后调用了,struts.xml 配置如下:
/success.jsp/error.jsp/regist.jsp
3.使用通配符处理
<action>的属性name class method 都支持通配符。struts.xml 配置如下:
/success.jsp/error.jsp/regist.jsp
关键就在于第三行代码, login_* 使用了通配符,所以接收所有类似的action请求,美国服务器,至于调用该类中的哪个方法,香港虚拟主机,就看method=”{1}”,表示使用name属性第一个*的值。例如,在本例中,form的action属性值设置为 login_regist,则调用com.main.action.LoginAction类中的regist()方法。
此外,Struts支持默认 Action 请求。当系统找不到指定的Action时,则交给默认的Action去处理。在struts.xml中的配置为:
<package …>
<default-action-ref></default-action-ref>
</package>
转自:
人生难免遇风雨,天空晴朗有阴云,别因雨水湿透衣衫而难过,