簡體   English   中英

Java Servlet DOM操作和html輸出

[英]Java servlet DOM manipulation and html output

我正在嘗試通過java servlet中的ID獲取html元素,並更改其內容,然后顯示文檔。 我的問題是我得到了元素並進行了設置(至少我這么認為),但是現在如何在瀏覽器中顯示它,這是我已經做過的事情:

@WebServlet(description = "profile page", urlPatterns = { "/profile/*" })
public class RouteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    String uri = request.getRequestURI();
    final String start = "/social/profile/";
    String userId = uri.substring(start.length());
    long id = Long.parseLong(userId);
    //response.getWriter().print(id);
    for (Info j : InfoRegistry.getInstance().getInfoList()) {
        if (j.getId() == id) {
            File template = new File("profile-template.html");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            Document doc;
            try {
                builder = factory.newDocumentBuilder();
                doc = builder.parse(template);
                doc.getDocumentElement().normalize();
                doc.getElementById("head").setTextContent(j.getName());
                doc.getElementById("name").setTextContent(j.getName());
                doc.getElementById("birth")
                        .setTextContent(j.getBirthDate());
                doc.getElementById("from").setTextContent(j.getCountry());
                doc.getElementById("desc").setTextContent(
                        j.getDescription());
                doc.getElementById("mail").setTextContent(j.getEmail());


            } catch (ParserConfigurationException e) {

                e.printStackTrace();
            } catch (SAXException a) {

                a.printStackTrace();
            }

        }
    }

}

}因此,使用現在設置的屬性,是否有任何問題,或者我應該怎么做才能顯示文件中的html?

好吧-您需要序列化文檔並將其發送回瀏覽器。 到目前為止,您擁有的一些代碼可以從磁盤讀取文件並在內存中進行操作。 為了將其發送到瀏覽器,您需要對其進行序列化,並使用從response.getWriter()獲得的PrintWriter將序列化的表示形式寫回到瀏覽器。

因此,基本問題是您的Servlet不會將任何內容發送回客戶端。

有關如何實施缺少的步驟的詳細信息,請參見此答案

我不建議從servlet進行此操作,您應該從瀏覽器發出Ajax請求以獲取一些數據,然后通過JQuery或簡單的javascript操作客戶端HTML,但是如果您決定使用這種方式,我建議您序列化您的文檔,然后通過PrintWritter將其發送給您的客戶端。 我更喜歡使用POJO映射功能來支持JSON響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM