當點擊一個超鏈接或提交一個HTML表單在Struts2 的 Web應用程序,輸入所收集被發送到一個Java類稱為操作控制器。當動作執行后,結果選擇了一個資源來呈現響應。資源通常是一個JSP,但它也可以是一個PDF文件,Excel電子表格,或一個Java applet 窗口。
假設已經建立開發環境?,F在讓我們繼續為第一個 “Hello World” 的 struts2 項目構建。這個項目的目的是建立一個Web應用程序,它收集用戶的姓名,并顯示“Hello World” 用戶名。我們將創建任何Struts2項目的四個組成部分:
我打算使用Eclipse IDE,所以所有必需的組件將創建一個動態Web項目下。所以,讓我們開始創建動態Web項目。
創建動態Web項目:
啟動Eclipse,然后再 File > New > Dynamic Web Project 輸入工程名稱為 HelloWorldStruts2 并設置屏幕中給出其余的選項:
選擇在接下來的畫面中的所有默認選項和最后檢查 Generate Web.xml deployment descriptor 選項. 這將創建一個動態Web項目在Eclipse?,F在去 Windows > Show View > Project Explorer, 會看到項目窗口的東西如下:
現在復制下列文件從struts 2 lib 文件夾 C:struts-2.2.3lib 到工程 WEB-INFlib 文件夾,要做到這一點,你可以簡單地將以下的所有文件拖放復制到WEB-INF lib文件夾。
- commons-fileupload-x.y.z.jar
- commons-io-x.y.z.jar
- commons-lang-x.y.jar
- commons-logging-x.y.z.jar
- commons-logging-api-x.y.jar
- freemarker-x.y.z.jar
- javassist-.xy.z.GA
- ognl-x.y.z.jar
- struts2-core-x.y.z.jar
- xwork-core.x.y.z.jar
創建動作類:
Action類是 Struts2 應用程序的關鍵,我們實現的大部分動作類中的業務邏輯。因此,讓我們創建一個Java文件HelloWorldAction.java Java Resources > src 在下面給出的內容包名 com.yiibai.struts2 。
Action類響應用戶操作,當用戶點擊一個URL。 Action類中的方法中的一個或多個被執行并返回一個字符串結果?;诮Y果的值,一個特定的JSP頁面的呈現方式。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.yiibai.struts2; public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success" ; } public String getName() { return name; } public void setName(String name) { this .name = name; } } |
這是一個非常簡單的類,一個名為“name”屬性。我們有標準的“name”屬性的getter和setter方法??,并返回字符串“success”的執行方法。
Struts2框架將創建一個對象HelloWorldAction類并調用執行方法在響應用戶的動作。把業務邏輯里面的execute方法,最后返回的字符串常量。簡單地說為每個網址,必須執行一個動作類,要么就可以直接使用這個類的名稱作為操作名,也可以使用struts.xml文件如下所示映射到一些其他的名字。
創建視圖
我們需要一個JSP提交最后的消息,這個頁面會被稱為Struts2框架一個預定義的動作時,會發生這種映射將被定義在struts.xml文件。因此,讓我們一起創造在Eclipse項目在WebContent文件夾下面的jsp文件helloWorld.jsp。要做到這一點,右鍵單擊WebContent文件夾在項目資源管理器,選擇New >JSP File。 .
1
2
3
4
5
6
7
8
9
10
|
<%@ page contentType= "text/html; charset=UTF-8" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value= "name" /> </body> </html> |
taglib指令告訴Servlet容器,這個頁面將使用Struts 2的標簽,這些標簽將之前由s。 s:property標簽顯示動作類屬性"name> HelloWorldAction類的getName()方法返回的值。
創建主頁:
我們還需要在WebContent文件夾中創建的index.jsp。該文件將作為初始動作URL,用戶可以在其中點擊告訴Struts 2框架調用 HelloWorldAction類定義的方法呈現 helloWorld.jsp 視圖。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action= "hello" > <label for = "name" >Please enter your name</label><br/> <input type= "text" name= "name" /> <input type= "submit" value= "Say Hello" /> </form> </body> </html> |
Hello 動作定義在上面的視圖文件將被映射到HelloWorldAction類和其執行方法使用struts.xml文件。當用戶點擊“提交”按鈕,將導致Struts2框架運行的執行方法定義的在其中,HelloWorldAction類根據返回值的方法,將相應的視圖選擇和渲染作為響應。
配置文件
我們需要一個映射,以配合網址,HelloWorldAction類(模型),和的helloWorld.jsp的(視圖)。映射講述了Struts 2框架類將響應用戶的操作(URL),這個類的方法將被執行,查看渲染基于字符串結果,該方法返回。
因此,讓我們創建一個名為struts.xml中。由于Struts2 要求struts.xml中存在類“文件夾中。因此,創建struts.xml文件的WebContent/ WEB-INF/classes文件夾下。 Eclipse不創建“classes”文件夾,所以需要自己做。要做到這一點,在項目資源管理器的WEB-INF文件夾上點擊右鍵并選擇New > Folder。struts.xml中應該像這樣:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> < struts > < constant name = "struts.devMode" value = "true" /> < package name = "helloworld" extends = "struts-default" > < action name = "hello" class = "com.yiibai.struts2.HelloWorldAction" method = "execute" > < result name = "success" >/HelloWorld.jsp</ result > </ action > </ package > </ struts > |
上面的配置文件的幾句話。在這里,我們設置為 true常量struts.devMode,因為我們正在程序開發環境,我們需要看到一些有用的日志消息。然后,我們定義了一個名為HelloWorld 包。創建一個包是有用的,當想一起進行分組動作。在我們的例子中,我們將我們的行動命名為“hello”,這是相應的URL /hello.action 和備份HelloWorldAction.class。執行HelloWorldAction.class方法是運行時URL /hello.action 調用的方法。如果執行方法的結果返回“success”,然后我們把用戶到 helloWorld.jsp。
下一步是創建一個web.xml文件,這是一個Struts2的任何請求的入口點。Struts2應用程序的入口點,將是一個部署描述符(web.xml)中定義的過濾器。因此,我們將定義在web.xml中條目oforg.apache.struts2.dispatcher.FilterDispatcher類。 web.xml文件中需要創建的WEB-INF文件夾下的WebContent下。已經建立的Eclipse的web.xml文件時為創建項目。所以,讓我們只需要修改如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < display-name >Struts 2</ display-name > < welcome-file-list > < welcome-file >index.jsp</ welcome-file > </ welcome-file-list > < filter > < filter-name >struts2</ filter-name > < filter-class > org.apache.struts2.dispatcher.FilterDispatcher </ filter-class > </ filter > < filter-mapping > < filter-name >struts2</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > </ web-app > |
我們已經指定index.jsp的歡迎文件。然后,我們已經配置Struts2的過濾器上運行的所有URL(即任何URL匹配模式/ *)
啟用詳細日志:
可以啟用完整的日志記錄功能,而Struts 2的WEB-INF/classes下文件夾創建logging.properties文件。保持在屬性文件中的以下兩行:
1
2
3
|
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler |
默認logging.properties指定ConsoleHandler的路由記錄到stdout,也是一個文件處理器。處理程序的日志級別閾值可以設置使用 SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST 或 ALL.
就是這樣。我們已經準備好使用Struts 2框架來運行我們的Hello World應用程序。
執行應用程序
右鍵點擊項目名稱,并單擊 Export > WAR File文件創建一個WAR文件。然后部署在Tomcat 的 webapps目錄下這個WAR。最后,啟動Tomcat 服務器和嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp。這會給出以下畫面:
輸入一個值“Struts2”,并提交頁面。應該看到頁面如下:
注意,可以定義索引struts.xml文件中的動作,在這種情況下,可以調用索引頁http://localhost:8080/HelloWorldStruts2/index.action。下面檢查如何定義指數作為一個動作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> < struts > < constant name = "struts.devMode" value = "true" /> < package name = "helloworld" extends = "struts-default" > < action name = "index" > < result >/index.jsp</ result > </ action > < action name = "hello" class = "com.yiibai.struts2.HelloWorldAction" method = "execute" > < result name = "success" >/HelloWorld.jsp</ result > </ action > </ package > </ struts > |
一個實例演示struts:學生學籍查詢(模糊查詢)
需求分析:查詢學生學籍,要涉及到數據庫的操作,要涉及到頁面的表單操作。
輸入學生名字,點擊模糊查詢。會返回查詢結果。
這里目的只是顯示struts的知識點。頁面操作等詳細細節不做過多要求。
在以上的基礎上,在temp包下新建QueryForm.java和QueryAction.java 在src下新建兩個包,一個是bean文件的,一個操作數據庫的,分別是com.bean和com.dao。com.bean下新建StudentBean.java文件com.dao下新建StudentDao.java文件
WebRoot新建queryform.jsp文件和result.jsp文件index.jsp可以做導航頁面(新建工程時既有)。
各個文件的內容如下:
StudentBean.java文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
package com.bean; //封裝一個學生的資料 public class StudentBean { private String stuId; private String stuName; private String stuSex; private String stuBir; private String stuAdd; public String getStuId() { return stuId; } public void setStuId(String stuId) { this .stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this .stuName = stuName; } public String getStuSex() { return stuSex; } public void setStuSex(String stuSex) { this .stuSex = stuSex; } public String getStuBir() { return stuBir; } public void setStuBir(String stuBir) { this .stuBir = stuBir; } public String getStuAdd() { return stuAdd; } public void setStuAdd(String stuAdd) { this .stuAdd = stuAdd; } } StudentDao.java文件: package com.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.bean.StudentBean; public class StudentDao { private Connection conn = null ; public void initConnection() { try { Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); conn = DriverManager .getConnection( "jdbc:sqlserver://localhost:1433;" + " DatabaseName=學生學籍信息" , "sa" , "sa" ); } catch (Exception e) { } } public ArrayList queryStuByName(String sname) { ArrayList stus = new ArrayList(); String sql = "select 學號,姓名,性別,出生年月," + "家庭住址 from 學籍表 where 姓名 like '%" + sname + "%'" ; //System.out.println("StudentDao.java中queryStuByName函數sname="+sname); try { this .initConnection(); ResultSet rs = conn.createStatement().executeQuery(sql); while (rs.next()) { StudentBean stu = new StudentBean(); stu.setStuId(rs.getString( "學號" )); stu.setStuName(rs.getString( "姓名" )); stu.setStuSex(rs.getString( "性別" )); stu.setStuBir(rs.getString( "出生年月" )); stu.setStuAdd(rs.getString( "家庭住址" )); stus.add(stu); } } catch (SQLException e) { e.printStackTrace(); } finally { this .closeConnection(); } return stus; } public void closeConnection() { try { if (conn != null ) { conn.close(); conn = null ; } } catch (Exception e) { e.printStackTrace(); } } } |
index.jsp文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<%@ page language= "java" import = "java.util.*" pageEncoding= "GB18030" %> <% 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> This is my JSP page. <br> <a href= "queryform.jsp" >學生學籍查詢</a> </body> </html> |
queryform.jsp文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<%@ page language= "java" import = "java.util.*" pageEncoding= "GB18030" %> <% 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 'queryform.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> 查詢表單 <br> <form action= "/Project02/query.do" method= "post" > 請您輸入學生姓名:<input name= "sname" > <input type= "submit" value= "模糊查詢" > </form> </body> </html> |
result.jsp文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<% @page import = "com.bean.StudentBean" %> <% @page import = "com.dao.StudentDao" %> <%@ page language= "java" import = "java.util.*" pageEncoding= "GB18030" %> <% 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 'queryform.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> |
返回結果頁面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
< br > <%ArrayList stus =(ArrayList)request.getAttribute("stus"); %> < table > < tr > < td > 學號 </ td > < td > 姓名 </ td > < td > 性別 </ td > < td > 出生年月 </ td > < td > 家庭住址 </ td > </ tr > <% for(int i=0;i< stus.size ();i++){ StudentBean stu=(StudentBean)stus.get(i); %> < tr > < td > <%=stu.getStuId() %> </ td > < td > <%=stu.getStuName() %> </ td > < td > <%=stu.getStuSex() %> </ td > < td > <%=stu.getStuBir() %> </ td > < td > <%=stu.getStuAdd() %> </ td > </ tr > <%} %> </ table > </ body > </ html > |
QueryForm.jsp文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
package project02; import org.apache.struts.action.ActionForm; //這是ActionForm為了容納表單的值 //規范: //1-必須繼承org.apache.struts.action.ActionForm //2-必須編寫和表單元素重名的元素屬性 //3-必須在Struts配置文件中注冊 @SuppressWarnings ( "serial" ) public class QueryForm extends ActionForm{ public QueryForm(){ System.out.println( "QueryForm.java構造函數運行" ); } private String sname; public String getSname() { System.out.println( "QueryForm.java中getSname函數運行" ); return sname; } public void setSname(String sname) { this .sname = sname; System.out.println( "QueryForm.java中setSname函數運行" ); } } queryAction.java文件: package project02; import java.util.ArrayList; 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.dao.StudentDao; //QueryAction負責接收ActionForm的數據,然后進行處理 //規則: //1-必須繼承org.apache.struts.action.Action //2-重寫excute方法業務邏輯 //3-將這個類在配置文件中注冊 public class QueryAction extends Action{ public QueryAction(){ System.out.println( "QueryAction.java構造函數運行" ); } @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { QueryForm queryForm=(QueryForm)form; String sname=queryForm.getSname(); sname= new String(sname.getBytes( "iso-8859-1" ), "gb2312" ); StudentDao studentDao= new StudentDao(); ArrayList stus=studentDao.queryStuByName(sname); request.setAttribute( "stus" , stus); System.out.println( "QueryAction.java中execute函數運行" ); // 跳轉 ActionForward af= new ActionForward( "/result.jsp" ); //設置了配置文件可以用以下方式跳轉 // ActionForward af = mapping.findForward("RESULT"); //以上方式出現異常警告:警告: Unable to find 'RESULT' forward. return af; } } |
編寫了以上的文件還未能實現struts的功能,要對各個文件之間的關系在struts-config.xml文件進行配置。
配置如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> < struts-config > < data-sources /> <!-- 在此注冊ActionForm --> < form-beans > <!-- name:名稱 type:類的路徑 --> < form-bean name = "queryForm" type = "project02.QueryForm" ></ form-bean > </ form-beans > < global-exceptions /> <!-- 設置URL的邏輯名稱 全局性的,所以的Action都可以識別到--> < global-forwards > < forward name = "RESULT" path = "/result.jsp" ></ forward > </ global-forwards > <!-- 這里注冊Action --> < action-mappings > <!-- name:Actionform的名稱 type:類的路徑 path:客戶端提交給服務器臨時指定的路徑 --> < action name = "queryForm" path = "/query" type = "project02.QueryAction" ></ action > </ action-mappings > < message-resources parameter = "project02.ApplicationResources" /> </ struts-config > |
最后,對工程文件進行發布,啟動tomcat,用瀏覽器測試。
現在,來梳理清楚。根據需求建立功能。根據要求建立form和action文件。最后對struts-config.xml文件進行配置。
測試操作步驟:
1-進入index.jsp導航頁面,點擊學生學籍查詢進入了queryform.jsp頁面
2-進入了queryform.jsp頁面,在文本框輸入學生名中的一個或兩個字進行模糊查詢。點擊模糊查詢。
<form action="/Project02/query.do" method="post">
請您輸入學生姓名:<input name="sname">
<input type="submit" value="模糊查詢">
</form>
Action:指定了action要執行的路徑 method:提交的方式--post不顯示信息,get顯示信息
3-進入了/Project02/query.do 到了QueryAction.java執行。這里為什么是到QueryAction.java文件下執行的呢?
1
2
3
4
5
6
7
8
9
10
11
|
<!-- 在此注冊ActionForm --> <form-beans> <!-- name:名稱 type:類的路徑 --> <form-bean name= "queryForm" type= "project02.QueryForm" ></form-bean> </form-beans> <!-- 這里注冊Action --> <action-mappings> <!-- name:Actionform的名稱 type:類的路徑 path:客戶端提交給服務器臨時指定的路徑 --> <action name= "queryForm" path= "/query" type= "project02.QueryAction" ></action> </action-mappings> |
因為配置文件已經完成了配置。注冊Action中的path=”/query”就是query.do只是沒有了.do后綴。這里已經指定了type類的路徑為:project02.QueryAction 所以執行QueryAction.java文件。
4-接下來的就是java文件了,大都能看懂。