天天看點

struts2學習筆記--動手搭建環境+第一個helloworld項目

  在Myeclipse中已經内置好了struts2的環境,但是為了更好的了解,這裡自己從頭搭建一下:

  前期準備:下載下傳struts2的完整包,下載下傳位址:

https://struts.apache.org/ ,解壓縮,在apps目錄下,解壓struts-blank.war包.

  • 第一步:導jar包:

    myeclipse中,建立一個web項目,将解壓好的struts-blank中的lib檔案夾下的所有jar包複制到項目的lib檔案夾下.然後Add to builtpath.

    算上日志相關的jar包,一共13個:

       

struts2學習筆記--動手搭建環境+第一個helloworld項目
  • 第二步,配置struts2的核心控制器web.xml:
  <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>      
  • 第三步,在src下添加名為struts.xml的配置檔案:

  檔案名不要改,可以自行添加,建議直接到下載下傳的完整包裡找一個項目,在src下拷貝它的struts.xml檔案到自己的項目,把多餘的東西删掉,隻留下這樣:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>


</struts>      

到這裡struts架構環境已經搭建完成了,現在我們來完成一個最簡單的hello-world項目:

  • 編寫Action類-我這裡命名為HelloAction:
package com.wang.action;

public class HelloAction {

    public String execute(){
        System.out.println("Hello World");
        return "success";
    }
}      

  注:在struts2中,預設執行execute方法,并且傳回類型為String類型,通路權限為public(龜腚).

  •  配置ACtion類-在struts.xml中,配置HelloAction
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="hello" extends="struts-default">
        <action name="hello" class="com.wang.action.HelloAction">
            <result name="success">/index.jsp</result>
        </action>
    </package>
    
</struts>      

如果在struts.xml中沒有代碼提示,可以在window->preferences->Myeclipse->Files and Editors->xml->xml catalog頁面内配置.dtd檔案(最好輸入xml,查找):

struts2學習筆記--動手搭建環境+第一個helloworld項目

這樣ALT+/就可以出現代碼提示了,完成後部署到Tomcat伺服器并啟動,打開浏覽器輸入http://localhost:8080/struts2_hello/hello,運作,就可以看到控制器列印出了helloWorld.