本文章環境:
1. Eclipse for JavaEE developer Helios
2. Struts 2.3.1.1
3. tomcat 7.0.6
配置前提:配置好tomcat,本文省略配置tomcat步驟
其實MyEclipse和Eclipse for JavaEE 的配置過程差不多,唯一的區別在於:
Eclipse for JAVAEE建立 Dynamic Web Projec;
MyEclipse建立的是Web Project;
1、建立一個Dynamic Web Project
2.點擊next
3.看到output folder為build\classes,和傳統的WEB-INF\classes有所差別,但是開發時不需要注意;
4. 在WEB-INF中配置web.xml,為了將Struts2架構添加入WEB應用; 在src中配置struts.xml(Eclipse在編譯時間會將src目錄下的除了Java檔案外的其他檔案全部拷貝進WEB-INF\classes) 將struts核心類庫匯入WEB-INF\lib中;
5.編寫web.xml
此處配置的目的是為了將struts2架構融入web應用,此處配置了一個過濾器,從前面學習可以知道,過濾器的作用是在Servlet執行之前完成一些事情,從<url-pattern>中可以看出任意的請求都會進入struts2的架構的範疇;
<?xml version="1.0" encoding="GBK"?><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" version="3.0"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
6.編寫struts.xml
<?xml version="1.0" encoding="GBK" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"><struts> </struts>
編寫Hello world
1.建立一個Hello.jsp 並且內容為Hello struts2!!!
2.配置struts.xml
<struts><constant name="struts.devMode" value="true"></constant> <package name="HelloPackage" namespace="/" extends="struts-default"> <action name="Hello"> <result>/Hello.jsp</result> </action> </package></struts>
3.部署並在瀏覽器中填寫 http://localhost:8888/StrutsDemo01/Hello
注意:在以後的開發中必須在<struts>元素中添加:
<constant name="struts.devMode" value="true"></constant>
因為這表明是在開發人員模式,是指發生錯誤時提供更多的提示資訊;