วันอังคารที่ 14 กุมภาพันธ์ พ.ศ. 2555

Struts 2 > Hello World Application

    ในแบบฝึกหัดนี้เราจะแสดงให้เห็นถึงวิธีการสร้าง Strust 2 แบบง่ายๆ ด้วย Hello World Application ก่อนการสร้างจะมีไฟล์ที่ประกอบการทำ Application ตามข้อมูลด้านล่างเลยครับ.

ไฟล์หลักๆ ในการทดสอบ  Hello World Application

  • web.xml
  • struts.xml
  • HelloWorld.java
  • index.jsp
  • success.jsp


รูปด้านล่างแสดงโครงสร้างของ Hello World Application



web.xml


<filter>
02.<filter-name>struts2</filter-name>
03.<filter-class>org.apache.struts2.dispatcher.FilterDispatcher </filter-class>
04.</filter>
05.<filter-mapping>
06.<filter-name>struts2</filter-name>
07.<url-pattern>/*</url-pattern>
08.</filter-mapping>
09.<welcome-file-list>
10.<welcome-file>index.jsp</welcome-file>
11.</welcome-file-list>

struts.xml

1.<struts>
2.<package name="default" extends="struts-default">
3.<action name="HelloWorld" class="com.blogspot.javathaitalk.HelloWorld">
4.<result name="SUCCESS">/success.jsp</result>
5.</action>
6.</package>
7.</struts>

index.jsp

01.<%@taglib uri="/struts-tags" prefix="s" %>
02. 
03.<html>
04.<head>
05.<title>Hello World</title>
06.</head>
07.<body>
08.<s:form action="HelloWorld" >
09.<s:textfield name="userName" label="User Name" />
10.<s:submit />
11.</s:form>
12.</body>
13.</html>

HelloWorld.java


01.public class HelloWorld {
02. 
03.private String message;
04. 
05.private String userName;
06. 
07.public HelloWorld() {
08.}
09. 
10.public String execute() {
11.setMessage("Hello " + getUserName());
12.return "SUCCESS";
13.}
14. 
15.public String getMessage() {
16.return message;
17.}
18. 
19.public void setMessage(String message) {
20.this.message = message;
21.}
22. 
23.public String getUserName() {
24.return userName;
25.}
26. 
27.public void setUserName(String userName) {
28.this.userName = userName;
29.}
30. 
31.}
ขันตอนของการ execute() method ของ class HelloWorld เราสามารถเข้าถึงข้อมูลของ properties ได้จาก Class นี้ซึ่งต่างจาก Struts 1 ที่ต้องมี Form. เราสามารถทำ Java class action ได้ง่ายๆ.

success.jsp

สำหรับ หน้า success เราจะทำการแสดงข้อความ "Hello คนไทย" โดยที่มันจะแสดงผ่าน property tag ที่ชื่อว่า message ด้านล่าง.
01.<%@taglib uri="/struts-tags" prefix="s" %>
02.<html>
03.<head>
04.<title>Hello World</title>
05.</head>
06.<body>
07.<h1><s:property value="message" /></h1>
08.</body>
09.</html>

Demo After Run Application

























* ถ้าใครต้องการ demo application ให้ comment และฝาก email ไว้นะครับ ผมจะส่งให้ทาง email.