4、在Action中定义多个方法
通常情况下,我们都将业务逻辑代码放在Action的execute方法中进行处理,但对于一些需要实现多个功能的Action,那么做就太不合适了。这个时候我们就需要根据不同的功能需求,在Action中定义多个方法。比如Action需要完成注册和登陆两项功能可以设计代码为:
package wwfy.action.user; public class UserAction { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String login() { // 只有用户名为wwfy,密码为123456方可成功登陆 if (username.equals("wwfy") && password.equals("123456")) { return "loginSuccess"; } else { return "loginError"; } } public String regist() { if (username.equals("") || password.equals("")) { return "registError"; } else { return "registSuccess"; } } }
在struts.xml中配置Action
<action name="loginUser" class="wwfy.action.user.UserAction" method="login"> <result name="loginSuccess">/jsp/loginSuccess.jsp</result> <result name="loginError">/jsp/loginError.jsp</result> </action> <action name="registUser" class="wwfy.action.user.UserAction" method="regist"> <result name="registSuccess">/jsp/registSuccess.jsp</result> <result name="registError">/jsp/registError.jsp</result> </action>
注意method中选择对应的方法。