使用Eclipse配置Struts2開發環境
Apache版本:apache-tomcat-6.0.37
Struts2:本次使用版本2.3.16.3.GA,下載地址http://struts.apache.org/download.cgi#struts23163
如上圖,選擇下載struts-2.3.16.3-all.zip並解壓
Eclipse和Tomcat的安裝不再細說了,注意看一下Struts2專案的配置:
1、建立動態web專案
在Eclipse中選擇File-New-Dynamic Web Project建立動態專案:
按下圖建立名稱為Struts2HelooWorld的專案,在Target runtime中選擇Apache Tomcat v6.0並按提示選擇Tomcat的安裝根目錄,單擊“Finish”完成專案建立
2、新增Struts2 庫到專案
在解壓的struts-2.3.16.3-all目錄下的lib目錄中複製需要的庫,並在Struts2HelloWorld專案的WebContent/WEB-INF/lib上右鍵貼上:
需要匯入的庫如下,每個庫的說明請參加struts2的文件:
3、配置過濾器
在Struts2HelloWorld專案的WebContent/WEB-INF/web.xml中新增如下配置:
如下:
- <filter>
- <filter-name>struts2</filter-name>
-
<
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
-
</filter-mapping
按下圖建立一個包:
在該包中增加一個HelloWorld類,實現xwork2的Action介面:
按如下內容編輯該類:
- package com.mystruts.action;
- import com.opensymphony.xwork2.Action;
- /**
- * @author david
- *
- */
- public class HelloWorld implements Action {
- private String message;
- /**
- * @return the message
- */
- public String getMessage() {
- return message;
- }
- /* (non-Javadoc)
- * @see com.opensymphony.xwork2.Action#execute()
- */
- @Override
- public String execute() throws Exception {
- // TODO Auto-generated method stub
- message = "Hello World!";
- return SUCCESS;
- }
- }
5、新增jsp頁面
在新增jsp檔案之前,首先我們修改一下eclipse的預設專案編碼,否則中文會是亂碼,修改方法如下:
選擇eclipse的主選單中的window-Preferences
JSP Files的編碼選擇UTF-8
然後新增HellowWorld.jsp檔案:
按下文編輯HelloWorld.jsp檔案:
- <%@ page language="java"contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <%@ taglib prefix="s"uri="/struts-tags" %>
- <html>
- <head>
- <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
- <title>歡迎介面</title>
- </head>
- <body>
- <h2><s:propertyvalue="message"/></h2>
- </body>
- </html>
6、新增struts.xml配置檔案:
檔案內容如下:
- <?xmlversion="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>
- <packagename="HelloWorld"extends="struts-default">
- <actionname="HelloWorld"class="com.mystruts.action.HelloWorld">
- <resultname="success">/HelloWorld.jsp</result>
- </action>
- </package>
- </struts>
7、除錯
在瀏覽器中輸入:http://localhost:8080/Struts2HelloWorld/HelloWorld
結果如下: