Struts是一個非常流行并被許多企業級應用程序采用的WEB框架,Struts2在Struts1.x的基礎上進行了大量改造,和WebWork合二為一,引進了更多的新觀念、新思想和新技術,使之更符合J2EE應用程序開發的需要。
學一門新技術時,第一個應用程序非常重要,本文簡單介紹了下struts2寫了一個hello world程序,并有部分講解希望能夠給struts愛好者提供一點點幫助
struts2與struts1.x有很大差異,struts2的配置文件為struts.xml相當于struts1中的struts-config.xml文件 其次放的位置也不同 struts.xml放在項目的src下面使用myeclipse發布的時候會自動復制到classes下面
struts.xml代碼
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="com.struts2.demo" extends="struts-default">
<action name="Hello" class="com.struts2.demo.Hello">
<result>/index.jsp</result>
</action>
<!-- Add your actions here -->
</package>
</struts>
將Struts2所帶的過濾器org.apache.struts2.dispatcher.FilterDispatcher配置到工程的web.xml文件中,默認情況下,該過濾器攔截請求字符串中以.action結尾的請求,并將該請求委托給指定的Action進行處理。最直觀的表現就是調用Action的execute()方法。代碼如下
<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>
我們的java文件 相當于使用struts1的action 但這里是繼承了ActionSupport 是webwork中的類
package com.struts2.demo;
import com.opensymphony.xwork2.ActionSupport;
public class Hello extends ActionSupport{
private String message;
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
public String execute() throws Exception{
setMessage("Hello my first Struts2 demo");
return SUCCESS;
}
}
注:ActionSupport是Struts2提供的類,功能類似于Struts1.x中的Action類,該類封裝了幾個有用的功能,比如:
getText():從資源文件中獲取國際化消息。
addFieldError():驗證輸入未通過時添加錯誤消息,支持國際化。
execute():該方法一般會被重寫,當客戶端向Action發送請求時,會調用此方法。
標簽名稱 說明
include 包含其他xml文件,在示例中,這意味著struts.xml可以訪問定義在struts-default.xml文件中的組件。
該元素可以使得Struts2定義多個配置文件,“分而治之”。
要注意的是,任何一個struts2配置文件都應該和struts.xml有相同的格式,包括doctype,并且可以放在類路徑下的任何地方。
package 為Action或截攔器分組。
name:名稱,必填項,名稱自定義,沒特別要求。方便別的package引用。
extends:package能繼承其他的package,即通過該屬性實現,值為另一個package的name。
在示例中,extends =”struts-default”是從struts-default.xml中繼承的。
action 定義Action,name屬性為訪問時用到的名稱,class屬性是Action的類名。
result 根據Action的返回值定義頁面導航。
Action的預定義的返回值有:
String SUCCESS = "success";
String NONE = "none";
String ERROR = "error";
String INPUT = "input";
String LOGIN = "login";
比如,當Action返回SUCCESS時希望轉到index.jsp頁面,則可以這樣寫:
<result name=”success”>index.jsp</result>
其中,name的缺省為success。
返回的頁面代碼
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h2><s:property value="message" /></h2>
</body>
</html>
最后訪問
http://127.0.0.1:8081/Hello.action 可能和你建的項目路徑不同
這樣就完成了一個hello world程序
還在學習中 如果有好的資料希望可以分享一下 最后還是希望可以提出寶貴意見