Friday, October 4, 2013

Lab – JSP - custom tag

Objectives


1. Create custom tag: Basis, Iteration and Complex tag


- Implement Interface
- Extend from Build in class

2. Using custom tag in JSP pages


Hits: Steps to create and call custom tag
1. Describe tag structure (Tag Library Description)
2. Process tag (Tag handler)
3. Register and call custom tag on JSP pages (<%@taglib ......%>

Custom tag 2013 (pdf version)


Source code

Create custom tag


1. Empty tag: header tag, footer tag
2. If – then – else tag
3. Iteration tag: loop tag
4. Employee list tag

HEADER tag (Implement Tag interface)


Create Tag Library Descriptor (customTag.tlb) file and insert xml section below
<tag>
<name>header</name>
<tag-class>MySource.header</tag-class>
<body-content>empty</body-content>
<attribute>
<name>companyname</name>
<required>true</required>
</attribute>
</tag>
Create tag handler
Create java class (header.java) in MySource package implement Tag interface
clip_image002
package MySource;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
public class header implements Tag{
String companyname ="";
public void setCompanyname(String companyname) {
this.companyname = companyname;
}

PageContext context;
Tag parrent;
public void setPageContext(PageContext pc) {
context = pc;
}

public void setParent(Tag t) {
parrent = t;
}

public Tag getParent() {
return parrent;
}

public int doStartTag() throws JspException {
try {
context.getOut().print("<h1>"+companyname+"</h1>");
context.getOut().print("<h3>Education Department</h3>");
} catch (IOException ex) {
Logger.getLogger(header.class.getName()).log(Level.SEVERE, null, ex);
}

return SKIP_BODY;
}

public int doEndTag() throws JspException {
return SKIP_BODY;
}

public void release() {
}

}

Call header from jsp page


Create jsp page (home.jsp), using taglib tag register header tag
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<%@taglib prefix="my" uri="/WEB-INF/MyLib.tld" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
</body>
</html>

Now build and run home.jsp page


clip_image004

Home.jsp

FOOTER tag (extend from Simple Tag Support class)


Create Tag Handler (footer.java)
clip_image006
Select Tag Handler from netbean template
clip_image008
Provide tag name as footer and click next
clip_image010
Click Browse to select tld file, click New to add companyname attribute as figure

Modified home.jsp as below


<%@page contentType="text/html" pageEncoding="windows-1252"%>
<%@taglib prefix="my" uri="/WEB-INF/MyLib.tld" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
<my:footer companyname="Can Tho University Software Center (CUSC)"/>
</body>
</html>

Now build and run home.jsp page


clip_image012
Home.jsp

Loop tag


Create Tag Handler (loop.java) extend from Simple Body Tag Support, with 2 attribute start and end
clip_image014
clip_image016

Modified writeTagBodyContent as below

private void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
if(start < end)
{
out.print("<ol>");
while(start < end)
{
out.print("<li>");
bodyContent.writeOut(out);
out.print("</li>");
start++;
}

out.print("</ol>");
}
bodyContent.clearBody();
}

Modified home.jsp as below
<%@page contentType="text/html" pageEncoding="windows-1252"%>
<%@taglib prefix="my" uri="/WEB-INF/MyLib.tld" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
<hr/>
<my:loop start="0" end="10">
<%= new java.util.Date()%>
</my:loop>
<my:footer companyname="Can Tho University Software Center (CUSC)"/>
</body>
</html>

Now build and run home.jsp page


clip_image018

Employee list tag


Create Tag Handler (employee.java) extend from Simple Body Tag Support (same above)
Modified employee.java as:
private void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn;
conn = DriverManager.getConnection("jdbc:sqlserver://ntdan-lt;user=sa;password=Admin@123;database=NorthWind;");
PreparedStatement command = conn.prepareStatement(bodyContent.getString());
java.sql.ResultSet result = command.executeQuery();
ResultSetMetaData meta = result.getMetaData();
out.print("<table border='1px'>");
out.print("<tr bgcolor='#ACE768'>");
int count = 1;
while(count <= meta.getColumnCount()) {
out.print("<td>"+meta.getColumnName(count)+"</td>");
count++;
}

out.print("</tr>");
while(result.next()) {
count=1;
out.print("<tr>");
while(count <= meta.getColumnCount()) {
out.print("<td>"+result.getString(meta.getColumnName(count))+"</td>");
count++;
}
out.print("</tr>");
}
out.print("</table>");
conn.close();
} catch(Exception ex) {
out.print(ex.toString());
}
bodyContent.clearBody();
}

Open home.jsp, insert code as

<body>
<my:header companyname="Can Tho University Software Center (CUSC)"/>
<hr/>
<my:loop start="0" end="2">
<%= new java.util.Date()%>
</my:loop>
<my:employee>Select Top 5 EmployeeID, FirstName, LastName From Employees</my:employee>
<my:footer companyname="Can Tho University Software Center (CUSC)"/>
</body>

Now build and run home.jsp page


clip_image020

8 comments:

  1. Thầy ơi, trong JSP làm thế nào để dữ liệu mình nhập vào textarea mà khi mình hiển thị lên trang view thì sẽ giống định dạng mình chọn hong thầy.
    VD: như em tab, enter hoặc cách khoản vậy

    ReplyDelete
  2. Dạ e cug in ra trong thẽ div, p mà cũng hong được thầy ơi.

    ReplyDelete
  3. Em muốn tạo giao diện nhập liệu thế này phải không?
    http://ckeditor.com/demo

    ReplyDelete
  4. dạ đúng vậy đó thầy

    ReplyDelete
  5. Trang nay hay qua thây oi, e lam dc ui, e cam on thây nhiu.

    - Mà Thầy ơi, e hiển thị dữ liệu bằng tiếng việt bị mã hóa hết àh, e đã định dạng UTF-8 xong hết rồi, nó cũng hong hiển thị được = tiếng việt,
    Em đã dùng class
    URLDecoder.encode(strValue,"UTF-8") và URLDecoder.decode(strValue,"UTF-8") thì hiển thị được. Nhưng chiều dài dữ liệu khi đã mã hóa luu vào dữ liệu dài quá àh, thầy biết cách nào hướng dẫn nge thầy!

    ReplyDelete
  6. tôi cũng chỉ làm cách em vừa nói thôi

    ReplyDelete
  7. hihi, e cam on thây nhiu

    ReplyDelete

Translate