速動畫教程第二十八集
Struts+Velocity
簡單集成
下載請到:http://this.oksonic.cn??討論請到 http://www.oksonic.com.cn? 注冊用戶后再轉到論壇
?
一.??
開發環境:
1.??????
jdk1.5.x
?????????????????
http://java.sun.com/j2se/1.5.0/download.jsp
2.??????
Eclipse3.2.1??????????? http://www.eclipse.org
3.??????
MyEclipse5.1.0?????? http://www.myeclipseide.com
4.??????
Tomcat5.5.20? ??????
http://tomcat.apache.org/
5.??????
Velocity1.4
????????????? http://velocity.apache.org/
6.??????
velocity-tools-1.3???
http://velocity.apache.org/site/tools/
?
二.??
開發步驟
1.??????
新建一個
web
項目
vm
2.??????
添加
struts
框架到項目中,使用
struts1.2
3.??????
拷貝
Velocity
包中的
velocity-1.4.jar
、
velocity-tools-view-1.3.jar
、
commons-collections-3.2.jar
、
velocity-tools-1.3.jar
文件到項目的
lib
目錄下,并刷新項目以載入包
4.??????
修改
web.xml
文件讓它識別
Velocity servlet
<
servlet
>
??????
<
servlet-name
>
velocity
</
servlet-name
>
??????
<
servlet-class
>
?????????? org.apache.velocity.tools.view.servlet.VelocityViewServlet
??????
</
servlet-class
>
???
</
servlet
>
???
<
servlet-mapping
>
??????
<
servlet-name
>
velocity
</
servlet-name
>
??????
<
url-pattern
>
*.vm
</
url-pattern
>
???
</
servlet-mapping
>
?
5.??????
創建一個
test
結構(
test.jsp
、
testForm.java
、
testAction.java
)
6.??????
修改
struts
配置文件,加入導航配置,跳專到
test.vm
文件,內容如下:
<
action-mappings
>
???
<
action
?????
attribute
=
"testForm"
?????
input
=
"/test.jsp"
?????
name
=
"testForm"
?????
path
=
"/test"
?????
scope
=
"request"
?
????
type
=
"com.oksonic.struts.action.TestAction"
>
?????
<forward name="success" path="/test.vm" />
?
</
action
>
?????
?
?
</
action-mappings
>
?
?
?
7.??????
修改
testAction.java
文件,代碼如下:
public
ActionForward execute(ActionMapping mapping, ActionForm form,
?????????? HttpServletRequest request, HttpServletResponse response) {
?????? TestForm testForm = (TestForm) form;
??????
//
對模型中的
test
屬性負值
?????? testForm.setTest(
"hello struts and velocity"
);
??????
//
將
form
對像存放到
request
對像中
?????? request.setAttribute(
"test"
, testForm);
??????
//
調用導航配置進行跳轉
??????
return
mapping.findForward(
"success"
);
?
??? }
?
8.??????
根據
struts-config.xml
文件中的
<
forward
name
=
"success"
path
=
"/test.vm"
/>
配置內容,需要在
webroot
目錄中新建一個
test.vm
文件此文件為
Velocity
模板文件,文件內容如下:
<%@
page
pageEncoding=
"utf-8"
%>
<%
request.setCharacterEncoding(
"utf-8"
);
%>
<html>
<head>
<meta
http-equiv=
"Content-Type"
content=
"text/html; charset=utf-8"
>
<title>
struts velocity
六月天
</title>
</head>
<body>
?
${test.getTest()}
?
</body>
</html>
?
其中
${test.getTest()}
為取得
testForm
對像中的
test
屬性值
?
三.??
測試
部署項目
在地址欄中輸入
http://localhost/vm/test.do
,頁面中顯示
hello struts and velocity
字樣
?
四.??
參考資料
《簡單
Velocity
實踐》來源于
internet
網絡
《
Struts
與
Velocity
的集成》來源于
internet
網絡
?
Velocity
模板的基本入門就到此,謝謝收看!
?