使用Struts1完成用戶登陸功能

一、Struts框架

框架(framework):就是一系列代碼和開發模式的整合,使用框架後,全部開發人員都會按照框架提供的規範進行開發,使代碼更容易維護和擴展。css

使用框架的優勢:html

1)   易於維護擴展java

2)   簡化代碼web

 

Struts框架是MVC模式的具體實現框架,實現針對MVC模式中的Servlet以及jsp頁面代碼的簡化。數據庫

 

JSP + Servlet 的執行流程:apache

jsp à web.xml中查找<servlet-mapping>找到進入哪一個Servlet à 執行doGet或doPost方法,接收參數,驗證,整合,調用service,設置屬性,跳轉 à 返回jsp。app

 

Struts執行流程中主要修改了Servlet部分,不須要再編寫Servlet,但須要創建Action和ActionForm,將Servlet中主要實現的功能也拆分爲兩部分,其中對於參數的處理交給ActionForm來執行,其餘操做由Action實現。框架

 

在jsp頁面上,再也不使用JSTL,改成Struts-Taglib,能夠替代JSTL標籤完成循環,判斷,格式化等操做,並擴展了新的功能,替代原有頁面表單,造成動態表單,支持自動回填功能。jsp

 

Struts不對數據庫操做代碼產生任何影響,DAO仍是使用原有的JDBC。post

 

二、使用Struts完成用戶登陸功能

假設用戶輸入用戶名爲zhangsan,密碼爲123表示登錄成功,不然登錄失敗。

創建項目,加入Struts1.3支持。

加入支持後,項目中多出如下內容:

1)   src下的資源文件(ApplicationResources.properties)

2)   支持類庫

3)   struts-config.xml

web.xml中加入ActionServlet配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 3   <display-name />
 4   
 5   <!-- Struts的配置 -->
 6   <servlet>
 7     <servlet-name>action</servlet-name>
 8     <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
 9     <init-param>
10       <!-- 能夠配置多個配置文件,中間使用逗號隔開 -->
11       <param-name>config</param-name>
12       <param-value>/WEB-INF/struts-config.xml</param-value>
13     </init-param>
14     <init-param>
15       <param-name>debug</param-name>
16       <param-value>3</param-value>
17     </init-param>
18     <init-param>
19       <param-name>detail</param-name>
20       <param-value>3</param-value>
21     </init-param>
22     <load-on-startup>0</load-on-startup>
23   </servlet>
24   <servlet-mapping>
25     <servlet-name>action</servlet-name>
26     <url-pattern>*.do</url-pattern>
27   </servlet-mapping>
28   
29   
30   <welcome-file-list>
31     <welcome-file>index.jsp</welcome-file>
32   </welcome-file-list>
33 </web-app>

 

若是想不使用MyEclipse加入支持,能夠從apache官方網站上下載開發包,從開發包中找到這些配置,並加入項目。

在index.jsp中導入struts的html標籤,並完成登錄表單

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>登錄頁面</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body>
25     <html:form method="post" action="login.do" >
26        <br>用戶ID:<html:text property="userid"></html:text>
27        <br>密碼:<html:password property="password"></html:password>
28        <br><html:submit value="登錄"></html:submit>
29     </html:form>
30   </body>
31 </html>

 

改成標籤形式,其中property就是以前普通元素的name。

下面創建提交後接收信息和處理的ActionForm與Action

 

path表示進入此Action以及ActionForm的提交路徑,以 / 開頭。

Input Source表示出錯後自動跳轉的錯誤頁路徑。

Finish完成後,會在struts-config.xml中自動生成配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
 3 
 4 <struts-config>
 5   <form-beans >
 6     <!-- 配置的LoginForm -->
 7     <form-bean name="loginForm" type="lq.wangzhen.struts.form.LoginForm" />
 8   </form-beans>
 9 
10   <global-exceptions />
11   <global-forwards />
12   <action-mappings >
13     <!-- Action配置選項,指定對應的跳轉路徑path,錯誤路徑input,和對應的form name -->
14     <action
15       attribute="loginForm"
16       input="/index.jsp"
17       name="loginForm"
18       path="/login"
19       scope="request"
20       type="lq.wangzhen.struts.action.LoginAction"
21       cancellable="true" />
22   </action-mappings>
23 
24   <message-resources parameter="lq.wangzhen.struts.ApplicationResources" />
25 </struts-config>

 

先編寫ActionForm接收參數,並驗證。

 1 /*
 2  * Generated by MyEclipse Struts
 3  * Template path: templates/java/JavaClass.vtl
 4  */
 5 package lq.wangzhen.struts.form;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 
 9 import org.apache.struts.action.ActionErrors;
10 import org.apache.struts.action.ActionForm;
11 import org.apache.struts.action.ActionMapping;
12 import org.apache.struts.action.ActionMessage;
13 public class LoginForm extends ActionForm {
14     /**
15      * 變量名稱和表單中的變量名稱一致,會自動的進行接收,但要編寫對應的setter和getter方法
16      */
17     private String userid;
18     private String password;
19     
20     public ActionErrors validate(ActionMapping mapping,
21             HttpServletRequest request) {
22         //驗證用戶名和密碼是否爲空
23         ActionErrors errors = new ActionErrors();
24         if(userid == null || "".equals(userid.trim())){
25             errors.add("useridErr",new ActionMessage("userid.null"));
26         }
27         if(password == null || "".equals(password.trim())){
28             errors.add("passwordErr", new ActionMessage("password.null"));
29         }
30         return errors;
31     }
32     public void reset(ActionMapping mapping, HttpServletRequest request) {
33         // TODO Auto-generated method stub
34     }
35     public String getUserid() {
36         return userid;
37     }
38     public void setUserid(String userid) {
39         this.userid = userid;
40     }
41     public String getPassword() {
42         return password;
43     }
44     public void setPassword(String password) {
45         this.password = password;
46     }
47     
48 }

 

validate方法會在接收完參數後由Struts自動調用,驗證返回的ActionErrors裏若是包含了錯誤信息,則Struts會自動根據配置的錯誤頁跳轉回頁面,而不進入Action。

錯誤信息經過ActionMessage,從資源文件中查找。

ApplicationResources.properties

1 userid.null=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A\uFF01
2 password.null=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A\uFF01

 

資源文件中不容許出現中文,所以必須對中文進行轉碼。

在index.jsp中,提示錯誤信息

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>登錄頁面</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body>
25     <html:form method="post" action="login.do" >
26        <br>用戶ID:<html:text property="userid"></html:text>
27        <font color="red"><html:errors property="useridErr"/></font> <!-- 配置用戶名錯誤信息 -->
28        <br>密碼:<html:password property="password"></html:password>
29        <font color="red"><html:errors property="passwordErr"/></font>  <!-- 配置密碼錯誤信息 -->
30        <br><html:submit value="登錄"></html:submit>
31     </html:form>
32   </body>
33 </html>

 

在property中傳入以前加入錯誤時設置的key值,就能夠取得該錯誤信息並顯示。

若是沒有加property,則會取得全部錯誤信息並顯示。

進入Action,在Action中實現其餘的操做。

 1 /*
 2  * Generated by MyEclipse Struts
 3  * Template path: templates/java/JavaClass.vtl
 4  */
 5 package lq.wangzhen.struts.action;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import lq.wangzhen.struts.form.LoginForm;
11 
12 import org.apache.struts.action.Action;
13 import org.apache.struts.action.ActionErrors;
14 import org.apache.struts.action.ActionForm;
15 import org.apache.struts.action.ActionForward;
16 import org.apache.struts.action.ActionMapping;
17 import org.apache.struts.action.ActionMessage;
18 
19 public class LoginAction extends Action {
20     public ActionForward execute(ActionMapping mapping, ActionForm form,
21             HttpServletRequest request, HttpServletResponse response) {
22         LoginForm loginForm = (LoginForm) form;
23         if(loginForm.getUserid().equals("wangzhen") && loginForm.getPassword().equals("123")){
24             //登錄成功
25             request.getSession().setAttribute("userid", loginForm.getUserid());
26             //跳轉到成功也,這裏只給出名稱,具體的路徑配置到struts-config.xml中
27             return mapping.findForward("success");
28         }else{
29             //登錄失敗,自動返回到失敗頁
30             //還須要保存錯誤信息
31             ActionErrors errors = new ActionErrors();
32             errors.add("loginErr", new ActionMessage("login.err"));
33             //手工保存錯誤信息
34             super.saveErrors(request, errors);
35             return mapping.getInputForward();
36         }
37     }
38 }

 

這裏配置了跳轉路徑,須要修改struts-config.xml,將success的路徑配置上。

 1  <!-- Action配置選項,指定對應的跳轉路徑path,錯誤路徑input,和對應的form name -->
 2     <action
 3       attribute="loginForm"
 4       input="/index.jsp"
 5       name="loginForm"
 6       path="/login"
 7       scope="request"
 8       type="lq.wangzhen.struts.action.LoginAction"
 9       cancellable="true" >
10         <forward name="success" path="/pages/success.jsp"></forward>
11       </action>

 

name是跳轉路徑名稱,就是Action中findForward()方法中傳入的值

path是具體跳轉路徑,必須以 / 開頭。

在index.jsp中提示錯誤信息

 1  <body>
 2   <font color="red"><html:errors property="loginErr"/></font>
 3     <html:form method="post" action="login.do" >
 4        <br>用戶ID:<html:text property="userid"></html:text>
 5        <font color="red"><html:errors property="useridErr"/></font> <!-- 配置用戶名錯誤信息 -->
 6        <br>密碼:<html:password property="password"></html:password>
 7        <font color="red"><html:errors property="passwordErr"/></font>  <!-- 配置密碼錯誤信息 -->
 8        <br><html:submit value="登錄"></html:submit>
 9     </html:form>
10   </body>
相關文章
相關標籤/搜索