在src下新建lee包,新建接口Action.java、类LoginAction.java
1.Action.java:
package lee;
public interface Action {
public static final String SUCCESS="success";
public static final String ERROR="error";
public String execute() throws Exception;
}
2.LoginAction.java:
package lee;
import com.opensymphony.xwork2.ActionContext;
public class LoginAction implements Action {
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 execute() throws Exception {
if (getUsername().equals("scott") && getPassword().equals("tiger") ) {
ActionContext.getContext().getSession().put("user" , getUsername());
return SUCCESS;
} else {
return ERROR;
}
}
}
五、修改struts.xml
<?xml version="1.0" encoding="GBK" ?>
<!-- 指定Struts 2配置文件的DTD信息 -->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<!-- struts是Struts 2配置文件的根元素 -->
<struts>
<!-- Struts 2的Action必须放在指定的包空间下定义 -->
<package name="myFirstTest" extends="struts-default">
<action name="Login" class="lee.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
说明:
1.package name可以随意设置
2.login.jsp里的action="Login"对应struts.xml中的action name="Login",相关的class是"lee.LoginAction",
即lee包下的LoginAction.class
3.LoginAction执行自身的execute(),若返回"success"则请求被转发到/welcome.jsp,
若返回"error"则请求被转发到/error.jsp