Simple sitemesh tutorial
Sitemesh ถ้าพูดง่ายๆก็คือ Template Engine ของภาษา Java นั่นเอง โดยหากย้อนกลับไปก่อนหน้านิด หลายๆคนอาจจะรู้จัก Velocity, FreeMaker เป็นต้น หรือว่าเอาให้ง่ายที่สุด sitemesh ก็คือ master page นั่นเอง เอาไว้ทำ layout ของเวปไซต์ของเรา โดยหลักการทำงาน สามารถดูจาก sitemesh
ตัวอย่างนี้จะเป็นการลองใช้ sitemesh กับ jsp
1. เริ่มต้นจากการ ดาวโหลด sitemesh จากนั้นทำการเพิ่ม .jar เข้าไปในไฟล์เดอร์ WEB-INF/lib
2. ทำการเพิ่ม sitemesh filter ในไฟล์ web.xml
1 2 3 4 5 6 7 8 9 10 | <filter> <filter-name>sitemesh</filter-name> <filter-class> com.opensymphony.module.sitemesh.filter.PageFilter </filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> |
3. สร้างไฟล์ decorators.xml ไว้ที่ /WEB-INF/decorators.xml
1 2 3 4 5 | <decorators defaultdir="/WEB-INF/decorators"> <decorator name="main" page="main.jsp"> <pattern>/*.jsp</pattern> </decorator> <decorators> |
ดังตัวอย่างนี้ เราจะสร้างไฟล์ decorator ชื่อว่า main.jsp เก็บไว้ยังโฟล์เดอร์ WEB-INF/decorators/ โดยจะใช้ไฟล์นี้เป็นตัวกำหนด layout ของทุกไฟล์ที่มีนามสกุลเป็น .jsp
แต่หากว่าเราต้องการระบุเป็นเฉพาะไฟล์ไป สามารถทำได้โดยการเปลี่ยนเป็น
<pattern>/index.jsp</pattern> <pattern>/home.jsp</pattern>
4. จากนั้นจะทำการสร้างไฟล์ main.jsp ไว้ที่ WEB-INF/decorators/ เพื่อเป็นไฟล์ที่กำหนด layout ของเรา
<head>
<title>
Lumidant.com - <decorator:title default="SiteMesh Tutorial Example" />
</title>
<style type="text/css">@import "css/global.css";</style>
<decorator:head />
<body>
<div id="header">
<h2><a href="http://www.lumidant.com/">Lumidant.com</a> Tutorials</h2>
</div>
<div id="content">
<decorator:body />
</div>
</body>
</html>ทำการสร้างไฟล์ main.jsp เพื่อเป็น layout ของเวป พร้อมทั้งใส่
ผลการทำงาน ฝั่ง server เมื่อได้รับ request จะทำการประมวลผล หน้าหลัก จากนั้นจะนำ code ส่วนของ body ของหน้าหลักมา แทนที่