使用Struts框架,實現用戶登錄功能

      前言:本篇文章是本人這周學習的一個小結,在自我總結的同時,但願也可以給其餘同窗帶來一點幫助。本文主要知識是參照書本上的知識點以及網上其餘博客文章,在上機操練後的所得,具體源碼主要來自http://blog.csdn.net/lovesummerforever/article/details/17348871css

本文主要包括如下三點:MVC設計模式基本概念、Struts工做原理、使用Struts框架實現用戶登錄具體實例操做。html

 

1、        MVC設計模式java

    在瞭解MVC模式以前,先要弄清楚什麼是設計模式。web

    設計模式是一套被反覆使用、多數人知曉的、代碼設計經驗的總結,模式必須是典型問題的解決方案。設計模式的做用是解決一類問題的成功經驗,是爲了可重用代碼、讓代碼更容易被他人理解、保證代碼的可靠性。數據庫

    MVC是一種流行的軟件設計模式,這種模式將應用程序實現分爲模型(Model)、視圖(View)和控制器(Controller)三個部分,主要特色是把顯示和數據分離,增長了軟件的可重用性。MVC設計模式具體如圖一:apache

 

圖一:MVC設計模式設計模式

一、  模型(Model)瀏覽器

    模型表示數據和業務處理,它能夠分爲數據模型和業務模型,分別表明應用程序的狀態和業務邏輯。模型對應的組件是JavaBean或者Java類,只需寫一次就能夠被多個視圖重用,減小了代碼的重複性。用一句話來講:模型就是實現系統中的具體功能模塊。app

二、  視圖(View)框架

    視圖是用戶看到的與之交互的界面,負責數據採集和處理用戶的請求。視圖只是做爲一種輸出數據並容許用戶操縱的方式,對應的組件是JSP或HTML文件。

三、  控制器(Controller)

    控制器是接受用戶端的請求,將模型和視圖聯繫在一塊兒,實現用戶請求的功能。對應的組件是Servlet,起承上啓下的樞紐做用。

 

2、        Struts工做原理

    Struts是第一個按照MVC設計模式搭建的Web開發框架,基於Struts開發的應用由三類組件構成:控制器組件、模型組件和視圖組件。具體模型如圖二:

圖二:Struts結構圖

一、  控制器組件

    控制器組件包括ActionServlet(核心控制器)和自定義的Action(表明一個用戶的操做)。ActionServlet的只要功能是將一個客戶端的請求映射到相應的Action,若是該Action配置了指定的ActionForm,那麼就在request中抓取數據填充到這個ActionForm,而後調用Action的execute方法。在execute方法執行完成後,ActionServlet將接受包括有下一個資源信息的ActionFoward對象,並將請求轉至下一個資源。

二、  視圖組件

    視圖組件包括JSP頁面、ActionForm和Struts標籤。視圖組件通常由JSP實現,還包括自定義的ActionForm類和Struts標籤。自定義的ActionForm類用於封裝頁面提交的數據,且ActionForm類須要在struts-config.xml中配置,從頁面得到輸入屬性與表單域name屬性值一致。

三、  模型組件

   模型組件包括定義和實現業務邏輯的接口和類。模型組件並不禁Struts提供,由普通的接口和JavaBean充當,須要用戶本身編碼實現。例如,用戶登錄時獲取用戶名和密碼並與數據庫中數值比較的接口等。

 

3、        使用Struts框架實現用戶登錄具體實例操做

一、 建立Web項目,添加Struts到項目

      首先建立一個Web項目,輸入項目名Struts_Login後,選擇MyEclipse工具中的MyEclipse菜單中的Project Capabilities->Add Struts Capabilities命令,具體如圖三:

圖三:添加Struts框架Jar包到項目

    在添加完Struts框架jar包文件後,系統爲自動產生struts-config.xml文件,並在web.xml中自動添加ActionServlet。

二、  實現登錄功能的ActionForm類和Action類編寫

    ActionForm主要用來封裝頁面輸入的表單信息,本例中只設置了用戶名和密碼兩個信息,具體類名是LoginActionForm。代碼以下:

package com.liu.struts;

import org.apache.struts.action.ActionForm;

public class LoginActionForm extends ActionForm {
    
     /**
     * 
     */
    private static final long serialVersionUID = 1L;
    //用戶名。  
    private String username;  
    //密碼。  
    private String password;  
     
    //設置密碼。  
    public void setPassword(String password) {  
       this.password = password;  
    }  
    //獲得用戶名。  
    public String getUsername() {  
       return username;  
    }  
    //設置用戶名。  
    public void setUsername(String username) {  
       this.username = username;  
    }  
    //獲得密碼。  
    public String getPassword() {  
     
       return password;  
    }  

}

    Action類主要是用來實現具體用戶操做的功能,本例中LoginAction類繼承Action,表示用戶的登錄操做。具體代碼以下:

package com.liu.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;

public class LoginAction extends Action{
    
    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.setAttribute("username", username);  
                  return mapping.findForward("success");  
           }catch(UserNotFoundException e)  
           {  
                  e.printStackTrace();  
                  request.setAttribute("msg","用戶不能找到,用戶名稱=[" +username +"+]");  
           }catch(PasswordErrorException e)  
           {  
                  e.printStackTrace();  
                  request.setAttribute("msg","密碼錯誤");  
           }  
             
           return mapping.findForward("error");  
    }  
}

三、  處理用戶登錄的業務邏輯層userManager類的書寫

    本例中用戶登錄成功的用戶名和密碼均爲admin,是直接寫在.java文件中的信息,沒有與數據庫中信息進行驗證交互,但弄清楚本例後,本身再去進行數據庫中信息驗證,具體步驟操做也是大同小異。

    userManager類具體源碼以下:

package com.liu.struts;

public class UserManager {
     public void login(String username,String password)  
     {  
            if(!"admin".equals(username))  
            {  
                   throw new UserNotFoundException();  
            }  
              
              
            if(!"admin".equals(password))  
            {  
                   throw new PasswordErrorException();  
            }  
     }  
}

UserNotFoundException具體代碼以下:

package com.liu.struts;

public class UserNotFoundException extends RuntimeException {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public UserNotFoundException() {  
    }  
 
    public UserNotFoundException(String message) {  
           super(message);  
    }  
 
    public UserNotFoundException(Throwable cause) {  
           super(cause);  
    }  
 
    public UserNotFoundException(String message,Throwable cause) {  
           super(message, cause);  
    }  
}

    PasswordErrorException具體代碼以下:

package com.liu.struts;

public class PasswordErrorException extends RuntimeException {
     /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public PasswordErrorException() {  
     }  
  
     public PasswordErrorException(String message) {  
            super(message);  
     }  
  
     public PasswordErrorException(Throwable cause) {  
            super(cause);  
     }  
  
     public PasswordErrorException(String message,Throwable cause) {  
            super(message, cause);  
     }  
}

      以上即是業務邏輯層處理用戶登錄的具體代碼。

 

四、 配置sturts-config文件

    具體Struts-config代碼以下:

<?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>  
       <form-bean name="loginForm" type="com.liu.struts.LoginActionForm"/>  
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings>  
       <action path="/login"  
              type="com.liu.struts.LoginAction"  
              name="loginForm"  
              scope="request"  
              >  
              <forward name="success" path="/Login_success.jsp"/>  
              <forward name="error" path="/Login_error.jsp"/>  
       </action>  
    </action-mappings>    
  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

    與是相關的Web.xml代碼以下(此處用的系統自動導入Struts的jar包文件,因此web.xml不須要配置,不過能夠參考看一下):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name />
  <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>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

六、 編寫視圖層JSP文件

    index.jsp源碼以下(此JSP文件爲登錄界面):

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
   <form action="login.do" method="post">  
   用戶:<input type="text" name="username"><br>  
   密碼:<input type="password" name="password"><br>  
   <input type="submit" value="登陸">  
</form>  
  </body>
</html>

    當用戶密碼或用戶名輸入錯誤時,跳轉到Login_error.jsp界面,具體源碼以下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login_error.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   <%--  
  <%=request.getAttribute("msg") %>  
  --%>  
    
  ${msg },登錄錯誤!!!  
  </body>
</html>

    當用輸入用戶名和密碼均正確時,跳轉到Login_success.jsp界面,具體源碼以下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login_success.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   ${username},登陸成功! 
  </body>
</html>

    附:下圖四是項目Struts_Login目錄結構,以下:

圖四:Struts_Login項目目錄結構

6、部署、運行項目

     首先開啓Tomcat服務,而後給Struts_Login項目配置具體Tomcat,完成這兩步後,在瀏覽器中輸入http://localhost:8080/Struts_Login便可獲得預期目標。具體步驟截圖及運行截圖以下:

圖五:打開Tomcat服務

圖六:給Struts_Login配置Tomcat

 

 

圖七:登錄界面

 

圖八:登錄成功界面

 

圖九:登錄失敗界面

    好了,以上就是使用Struts框架,實現用戶登錄功能的具體步驟,寫了兩個小時終於把本文寫完了~

相關文章
相關標籤/搜索