1、搭建struts运行环境
1)建立Web项目,将struts相关包引入到项目中
2)将
struts-config.xml配置文件复制到项目中
3)在
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>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2、建立相关ActionForm及Action对象
1)
Action
Form对象
/** * 登陆ActionForm,负责表单数据收集 * 其继承:org.apache.struts.action.ActionForm * 注意:表单的属性必须和ActionForm中的get和set的属性一致 */ public class LoginActionForm extends ActionForm { 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; } }
2)Action对象
/** * 登陆Action * 负责取得表单数据、调用业务逻辑、返回转向信息 */ public class LoginAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //接收前台传递过来的数据 LoginActionForm laf=(LoginActionForm)form; //获取表单数据 String userName=laf.getUserName(); String password=laf.getPassword(); UserManager userManager=new UserManager(); try{ //调用业务处理对象的登陆方法 userManager.login(userName, password); //将数据设置到request中,以在前台jsp中获取显示 request.setAttribute("userName", userName); //成功则转向到成功界面 return mapping.findForward("success"); }catch(Exception e){ e.printStackTrace(); } //失败则转向到失败界面 return mapping.findForward("error"); } }
3、配置struts-config.xml文件
<struts-config>
<form-beans >
<form-bean name="loginForm" type="com.tgb.struts.LoginActionForm" />
</form-beans>
<action-mappings>
<action path="/login" type="com.tgb.struts.LoginAction"
name="loginForm"
scope="request">
<forward name="success" path="/login_success.jsp" />
<forward name="error" path="/login_error.jsp" />
</action>
</action-mappings>
</struts-config>
解释:上面 form-bean 配置的就是第二步建立的 LoginActionForm 对象
Action配置的就是第二步建立的 LoginAction 对象,在其属性name指向的就是配置的 form-bean。
forward 就是要转向的前端页面
4、在界面调用
<form action="login.do" method="post">
<input type="text" name="userName" ><br>
<input type="text" name="password"><br>
<input type="submit" value="登陆">
</form>