将struts部署完成后
一、在工程中建立一个包com.myf.demo.actionForm
建一个类LoginForm,此类继承ActionForm类(org.apache.struts.action.ActionForm),可以重写public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)方法,此方法用来处理检验信息,当返回为null时继续执行对应的actionservlet,当然validate方法可以不重写,看需要
定义两个变量,变量名字与jsp页面form表单中的名字相同
private String userName;
private String userPwd;
实现get、set方法
二、在工程中建立一个包com.myf.demo.actionServlet
建立一个类LoginAction此类继承Action类(org.apache.struts.action.Action),重写public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)方法
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
//将 ActionForm转换成对应的form
LoginForm f = (LoginForm)form;
String name = f.getUseName();
String pwd=f.getUsePwd();
//进行检验用户名和密码
if(name.equals("mou")&&pwd.equals("123")){
//检验成功
request.getSession().setAttribute("myid", p);
//跳转success对应的页面,success在xml中定义
return mapping.findForward("success");
}else{
//失败,跳转fail对应的页面
return mapping.findForward("fail");
}
}
三、更改struts-config.xml
<form-beans>
<form-bean name="loginForm" type="com.myf.demo.actionForm.LoginForm">
</form-bean>
</form-beans>
<action-mappings>
<action path="/login" type="com.myf.demo.actionServlet.LoginAction" name="loginForm">
<forward name="success" path="/success.jsp"></forward>
<forward name="fail" path="/fail.jsp"></forward>
</action>
</action-mappings>
四、jsp页面
<form action="<%=path %>/login.do" method="get">
用户名:<input type="text" name="useName"/><br/>
密码: <input type="password" name="usePwd"/>
<input type="submit" value="提交"/>
</form>
或者使用struts自带标签库
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html:form action="/MyStruts.do">
用户名:<html:text property="userName"></html:text><br/>
密码:</html:password></br>
<html:submit>提交</html:submit>
</html:form>