Struts1中实现登录实例_Struts1

添加支持(即jar包)后的步骤为:

(1)创建ActionForm

LoginForm.java

package com.mstf.struts.form;

import org.apache.struts.action.ActionForm; 

public class LoginForm extends ActionForm {

          String username; 

           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)创建控制器

LoginAction.java

package com.mstf.struts;

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.mstf.struts.form.LoginForm;

public class LoginAction extends Action {

 public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

  //将ActionForm强制类型转换为LoginForm,并获取传过来的表单

  LoginForm lgForm=(LoginForm)form;

  //获取表单元素的值

  String username=lgForm.getUsername();

  String password=lgForm.getPassword();

  //模拟调用javabean进行业务处理

  if("scce".equals(username) && "123456".equals(password)){

   return mapping.findForward("suc");

  }else{

   return mapping.findForward("fail");

  }

     } 

}

(3)创建视图

login.jsp

<body> 

  <form action="login.do">

   <p>用户名:<input name="username"></p>

   <p>密码:<input type="password" name="password"></p>

   <input type="submit" value="登录">

  </form>

</body>

success.jsp

<body> 

    <h1>登录成功</h1>

     <h1>用户名:${lf.username }</h1>

     <h1>密码:${lf.password }</h1>

 </body>

fail.jsp

<body>

   <h1>用户名或密码错误!请点击<a href="login.jsp">登录</a>重新登录。</h1>

</body>

(4)配置Struts1应用程序

<struts-config> 

  <data-sources />

  <form-beans >

   <!-- 配置loginForm -->

   <form-bean name="lf" type="com.mstf.struts.form.LoginForm"></form-bean>

  </form-beans>

  <global-exceptions />

  <global-forwards />

  <action-mappings >  

  <!--配置请处理的action-->

   <action path="/login" scope="session" attribute="lf" name="lf" type="com.mstf.struts.LoginAction">

    <!-- 配置转发页面 -->

    <forward name="suc" path="/success.jsp"></forward>

    <forward name="fail" path="/fail.jsp"></forward>

   </action>

  </action-mappings>

  <message-resources parameter="com.mstf.struts.ApplicationResources" />

</struts-config>

(5)发布、运行示例

Struts1中实现登录实例_Struts1_02

Struts1中实现登录实例_Struts1_03

Struts1中实现登录实例_Struts1_04