一、引入struts包
二、在WEB-INF目录下编写简单的login.jsp页面(V层);
<form action="/Strutstest/login.do" method="post">
U:<input type="text" name="username"/><br/>
P:<input type="password" name="password"/><br/>
<input type="submit" value="login"/>
</form>
三、创建用户表单类UserForm存放数据(M层,类似domian/javabean层):
Java代码
/**
* 用户表单类,用于填充数据
*/
package com.lh.forms;
import org.apache.struts.action.ActionForm;
public class UserForm extends ActionForm {
//在这里为了规范:定义属性名时应该和JSP页面的控件名称一样
//实际只需保证set和get方法和属性名有关联 set属性名
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;
}
}
四、编写LoginAction,继承Action,对应UserForm表单。(C层,处理请求,类似mvc中servlet)
Java代码
package com.lh.actions
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 com.lh.forms.UserForm;
/**
* 登陆Action,用于处理登陆请求
*/
public class LoginAction extends Action{
//execute自动调用,
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//将Form强转为UserForm
UserForm userForm = (UserForm)form;
String password = userForm.getPassword();
if("132".equals(password))
return mapping.findForward("OK");
else
return mapping.findForward("ON");
}
}
五、在WEB-INF下新建一个名为config的文件夹,在config文件夹里面创建名为struts-config.xml文件(建立Action和ActionForm 的对应关系);
Xml代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-Apache Software Foundation//DTD struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<!-- 配置表单 -->
<form-beans>
<!-- name为表单名字,可以随意,建议取名:表单类名的小写 -->
<!-- type用于指定表单类的全路径 -->
<form-bean name="userForm" type="com.lh.forms.UserForm"></form-bean>
</form-beans>
<!-- 配置action -->
<action-mappings>
<!-- path:将来访问action的uri name必须和表单名相同,用于关联某个表单 type:指定action的全路径-->
<!-- scope:指定该action对应的表单对象的生命周期为request级别 ,默认为session-->
<action path="/login" name="userForm" scope="request" type="com.lh.actions.LoginAction">
<!-- 这里配置跳转关系 name:结果名称 path:转发页面-->
<forward name="ok" path="/WEB-INF/ok.jsp"></forward>
<forward name="error" path="/WEB-INF/error.jsp"></forward>
</action>
</action-mappings>
</struts-config>
六、配置WEB-INF目录下的web.xml文件,配置struts入口
Xml代码
<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/config/struts-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
七、最后在WEB-INF目录下编写ok.jsp和error.jsp页面
Html代码
<body> Oh_ my god! </body>