必须的包: (版本可不一样)
struts-core1.3.5.jar
commons-beanutils-1.7.0.jar
commons-digester-1.8.jar
commons-logging-api-1.1.jar
commons-chain-1.1.jar
1。在web.xml中添加servlet
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> <!--根据自己需要确定--> </init-param> <load-on-startup>2</load-on-startup> <!--装载的优先级 0-5递减--> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
2. 编写前端页面 如login.jsp
写一个form表单
<form name="loginform" action="LoginAction.do">
<!--name 后边的struts配置文件中的form name一样-->
用户名:<input type="text" name="username">
<br>
密码:<input type="password" name="pwd">
<br>
<input type="submit" value="提交">
</form>
3.建立struts的配置文件 WEB-INF/struts-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="loginform" type="cn.netjava.form.LoginForm"></form-bean> </form-beans> <action-mappings> <action path="/LoginAction" type="cn.netjava.action.LoginAction" name="loginform"> <forward name="loginOK" path="/loginOK.jsp"></forward> // 登陆成功跳到 loginOK.jsp <forward name="loginFail" path="/loginFail.jsp"></forward> //登陆失败跳到 LoginFail.jsp </action> </action-mappings> </struts-config>
4. 编写 form类 LoginForm
package cn.netjava.form;
import org.apache.struts.action.ActionForm;
public class LoginForm extends ActionForm{
private String username; //对应jsp页面的那些属性
private String pwd;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
5.编写Action 为LoginAction
package cn.netjava.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import cn.netjava.formbean.LoginFormBean;
public class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("执行到这里");
LoginFormBean lfb =(LoginFormBean)form;
String username = lfb.getUsername();
String pwd = lfb.getPwd();
if("netjava".equals(username)&&("netjava".equals(pwd))){
return mapping.findForward("loginOK");
}
else{
return mapping.findForward("loginFail");
}
}
}