Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Các bước tạo 1 servlet dùng JSP để tạo 1 trang XML

Các bước tạo 1 servlet dùng JSP để tạo 1 trang XML

Trong bài viết này, chúng ta dùng Eclipse 3.3, Tomcat 6.

Đầu tiên, mở 1 project trong Eclipse J2EE bằng cách vào menu file, chọn New Project, chọn tiếp Dynamic Web Project.

Tiếp theo ta có màn hình sau

Trong trường hợp target runtime không có server nào thì ta có thể nhấn nút New bên cạnh sẽ có mà hình sau

Nhấn nút next để cấu hình vị trí lưu trữ Server trên đĩa cũng như JRE

Nhấn Finish để kết thúc cấu hình server.

Như vậy ta đã có Server và chúng ta đang ở bước tạo 1 web project

Gõ tên của project, nhấn nút next ta được

Nhấn tiếp nút Next, ta có thông tin về project như hình sau

Nhấn nút Finish để kết thúc việt tạo project. Trên package explorer ta được cấu trúc project như sau

Tiếp theo, để tạo 1 Servlet, ta nhấn chuột phải lên project của chúng ta, chọn New, chọn tiếp Other. Cửa sổ sau xuất hiện.

Tìm đến mục Web->Servlet, nhấn Next

Gõ vào package, class name sau đó nhấn Next

Có thể gõ vào description cho servlet hoặc không. Chú ý ở mục URL Mappings, đây là tên mapping của servlet. Ta có thể thay thế hoạc thêm vào tên khác.

Nhấn Next để chọn lựa các methods cho servlet

Nhấn Finish để kết thúc việt tạo 1 project. Ta sẽ có 1 lớp được thêm vào trong 1 gói như hình

Tiến hành gõ code vào như sau:

package mySVL;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class DOMXMLTree extends HttpServlet

{

private static final long serialVersionUID = 1L;

Document doc = null;

Element player = null;

Element country = null;

Element score = null;

public void init(ServletConfig config) throws ServletException

{

try{

doc = (Document)Class.forName(“org.apache.xerces.dom.DocumentImpl”).newInstance();

}catch (ClassNotFoundException cnfe){

System.err.println(cnfe);

}

catch(Exception e)

{

System.err.println(e);

}

if(doc != null)

{

Element root = doc.createElement(“Players”);

root.setAttribute(“type”, “Cricket”);

player = doc.createElement(“player”);

Element firstname = doc.createElement(“first-name”);

firstname.appendChild(doc.createTextNode(“Sunil”));

player.appendChild(firstname);

Element lastname = doc.createElement(“last-name”);

lastname.appendChild(doc.createTextNode(“Gavaskar”));

player.appendChild(lastname);

Element country = doc.createElement(“country”);

country.appendChild(doc.createTextNode(“India”));

player.appendChild(country);

root.appendChild(player);

doc.appendChild(root);

}

}

public void printDomTree(Node node, PrintWriter out)

{

int type = node.getNodeType();

switch (type)

{

//prints the document element

case Node.DOCUMENT_NODE:

{

printDomTree(((Document)node).getDocumentElement(),out);

break;

}

case Node.ELEMENT_NODE:

{

out.print(“<“);

out.print(node.getNodeName());

NamedNodeMap att = node.getAttributes();

for(int ctr = 0;ctr < att.getLength(); ctr++)

{

Node child = att.item(ctr);

out.print(” “ + child.getNodeName() +

“=\”” + child.getNodeValue() + “\””);

}

out.print(“>”);

NodeList children = node.getChildNodes();

if (children != null)

{

int length = children.getLength();

for(int ctr=0; ctr < length; ctr++)

{

printDomTree(children.item(ctr),out);

}

}

break;

}

// print text

case Node.TEXT_NODE:

{

out.print(node.getNodeValue());

break;

}

}

if(type==Node.ELEMENT_NODE)

{

out.print(“</”);

out.print(node.getNodeName());

out.print(“>”);

}

}

public void service(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException

{

response.setContentType(“text/xml”);

PrintWriter out = response.getWriter();

out.println(“<?xml version=\”1.0\” ?>”);

printDomTree(doc,out);

}

}

Đến đây ta có thể chạy ứng dụng bằng cách nhấn phải chuột lên file java của chúng ta, chọn Run as->Run On Server, chọn Tomcat Server ta có thể xem được kết quả. Nhưng bây giờ ta sẽ thiết kế 1 trang JSP để triệu gọi Servlet này như sau:

Nhấn chuột phải lên project, chọn new->Other như bước trên nhưng ở đây thay vì chọn Servlet ta chọn JSP, nhấn nút Next ta có

Gõ vào tên trang rồi nhấn Finish để kết thúc. Ta được 1 trang JSP. Sau đó gõ code sau vào phần body

<body>

<form action=“DOMXMLTree” method=“post”>

<h2>Click here to view XML document from servlet</h2>

<input type=“submit”/>

</form>

</body>

Lưu lại, sau đó nhấn chuột phải lên trang jsp, chọn Run as->Run On Server, chọn Tomcat, nhấn Finish ta có kết quả sau:

Nhấn nút Submit Query ta được

Như vậy ta đã xong công việc. Chúc các bạn thành công !

9 Responses to “Các bước tạo 1 servlet dùng JSP để tạo 1 trang XML”

  1. conghoat said

    Chào bạn. Tôi làm theo như hướng dẫn của bạn thì chỉ chạy được trang jsp. Sau đó click vào Submit Query thì nó link đến trang servlet và báo lỗi sau:

    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    java.lang.NullPointerException
    HelloServlet.printDomTree(HelloServlet.java:116)
    HelloServlet.service(HelloServlet.java:225)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:820)

    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.

    ——————————————————————————–

    Apache Tomcat/6.0.16

    Giúp tôi xử lý lỗi này với.
    Xin cảm ơn bạn.

  2. vovanhai said

    Bạn có đảm bảo trong classpath của bạn có tham chiếu đến file jar chứa đối tượng org.apache.xerces.dom.DocumentImpl không?
    Kiểm tra thử nhé! Nó nằm trong gói xerces.jar.
    Chúc thành công!

  3. phuc said

    blog của bạn có rất nhiều kiến thức tôi cần, thanks bạn rất nhiều

  4. NguyenHoang said

    Chào bạn, mình đang làm đồ án môn học về web viết = servlet và jsp kết nối với MySQL theo mô hình MVC. Mình đang điên đầu vì Ecllipse báo những lỗi hết sức khó chịu, hơn nữa, MySQL lại ko hiễn thị đc tiếng việt. Rất mong bạn có thể vài demo source qua mail giúp mình.

  5. vovanhai said

    Mô hình MVC thì tôi nghĩ bạn nên dùng theo 1 Framework nào đó chẳng hạn Struts hoặc spring. Tôi đã có vài demo trên đó rồi. Chúc vui!

  6. duy said

    chào anh Hải.sao khi em chạy thì trên trang web có 1 thông báo:This XML file does not appear to have any style information associated with it. The document tree is shown below.
    và nó không có dòng.vậy nghĩa là sao hả anh?

  7. Võ Văn Hải said

    Có lẽ là do trình duyệt. Nó yêu cầu bạn gán 1 style-sheet cho việc hiển thị XML thay vì hiển thị dạng “thô”. Bạn thử trình duyệt khác thử.

  8. Huỳnh Công Tiến said

    Em chào thầy Hải. Thầy ơi em start Server Tomcat v7.0 mà nó cứ báo lỗi này: “Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.” Em đã tăng thời gian timeout lên, và thử dùng JBoss nhưng kết quả cũng vậy. Mong thầy giúp. Em cám ơn thầy.

  9. van said

    em thưa thầy bài của em bị lỗi thế này thì sửa sao ạ
    HTTP Status 404 – /test/servlet/mySVL.DOMXMLTree

    ——————————————————————————–

    type Status report

    message /test/servlet/mySVL.DOMXMLTree

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/7.0.42

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.