在Servlet代碼中輸出HTML響應

jopen 9年前發布 | 35K 次閱讀 Servlet Java開發

如果你的企業級WEB應用中只是需要對大量的請求URI進行處理的話,那么在Servlet代碼里面直接生成HTML響應貌似要更簡單一些,而不必使用一套完整成熟的模板庫。在下面的例子中,我在Servlet代碼里用了一個非常簡單的Java DSL來生成HTML的輸出。代碼如下:

package zemian.servlet3example.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/index")
public class IndexServlet extends HtmlWriterServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HtmlWriter html = createHtmlWriter(req, resp);
        String message = getMessage(req, html);

        html.header()
            .h(1, "Welcome to Servlet 3 Example")
            .p("Let's explore Java Servlet 3.x Features.")
            .p(message)
            .ul(
                html.link("Index", "/index"),
                html.link("Hello", "/hello"),
                html.link("Form", "/form"),
                html.link("Sys Props (Password needed)", "/sys-props")
            )
            .footer();
    } 
}

我實現了一個叫作HtmlWriterServlet的基類,它提供了一個方法可以用來獲取HtmlWriter生成器的實例。封裝這么一個 HTML風格的生成器的好處是可讀性強,而且對于正確地生成表單標簽也很有幫助。比如說,可以給"ul"及"table"標簽傳入Java的List或者 Map對象,然后生成器便能輸出正確的html標簽。

在下面這個例子中,我只用了幾行代碼便生成了一個Java系統屬性的表格視圖頁:

package zemian.servlet3example.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/index")
public class IndexServlet extends HtmlWriterServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HtmlWriter html = createHtmlWriter(req, resp);
        String message = getMessage(req, html);

        html.header()
            .h(1, "Welcome to Servlet 3 Example")
            .p("Let's explore Java Servlet 3.x Features.")
            .p(message)
            .ul(
                html.link("Index", "/index"),
                html.link("Hello", "/hello"),
                html.link("Form", "/form"),
                html.link("Sys Props (Password needed)", "/sys-props")
            )
            .footer();
    } 
}

這個簡單的HtmlWriter提供了一些html的生成器方法,它可以根據上下文的相對路徑來生成HTML鏈接。你還可以完善下它,以便能生成更多的HTML代碼,比方說表單等。

還有一點需要注意的是,ServletResponse對象讓你能夠自由地定制輸出的響應結果,因此你不一定要返回HTML。你還可以生成二進制的輸出流,譬如PDF甚至MP3什么的。你只需控制好響應的寫入器以及內容的MIME類型及大小就好了。

上述代碼可以從這里獲取到。

原創文章轉載請注明出處:在Servlet代碼中輸出HTML響應

英文原文鏈接

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!