2010-03-03 82 views

回答

32

你需要有一個doGet方法爲:

public void doGet(HttpServletRequest request, 
     HttpServletResponse response) 
throws IOException, ServletException 
{ 
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 

    out.println("<html>"); 
    out.println("<head>"); 
    out.println("<title>Hola</title>"); 
    out.println("</head>"); 
    out.println("<body bgcolor=\"white\">"); 
    out.println("</body>"); 
    out.println("</html>"); 
} 

你可以看到this鏈接,一個簡單的Hello World servlet的

+12

不建議用這種方式從servlet生成HTML。這是一個1998年的老式成語。更好的解決方案是使用JSP。 – duffymo 2010-03-03 12:11:37

+2

或者使用一些像dojo,GWT等框架/工具,並保持客戶端的html與服務器端代碼完全分離。 – saugata 2010-03-03 12:40:21

+1

@duffymo:但有時,在某些場合,我想從Servlet生成正在進行的html響應。不是每個人都適合MVC。 – 2017-09-28 04:07:13

93

您通常將請求轉發給JSP顯示。 JSP是一種視圖技術,它提供了一個用於編寫普通香草HTML/CSS/JS的模板,並提供了在taglibs和EL幫助下與後端Java代碼/變量進行交互的能力。您可以使用像JSTL這樣的taglib來控制頁面流。您可以將任何後端數據設置爲任何請求,會話或應用程序範圍中的屬性,並在JSP中使用EL(${})來訪問/顯示它們。

開球例如:

@WebServlet("/hello") 
public class HelloWorldServlet extends HttpServlet { 

    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     String message = "Hello World"; 
     request.setAttribute("message", message); // This will be available as ${message} 
     request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response); 
    } 

} 

而且/WEB-INF/hello.jsp樣子:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <title>SO question 2370960</title> 
    </head> 
    <body> 
     <p>Message: ${message}</p> 
    </body> 
</html> 

當打開http://localhost:8080/contextpath/hello這將顯示

Message: Hello World
在瀏覽器

這使Java代碼免於HTML雜亂並大大提高了可維護性。要通過servlet學習和實踐更多,請繼續閱讀下面的鏈接。

也瀏覽the "Frequent" tab of all questions tagged [servlets]找到常見問題。

+2

這仍然是一個有效的方法嗎?我總是聽到我們的首席架構師說不使用JSP,但是我問自己應該如何創建所有的HTML?以編程方式逐個創建每個元素?這可能需要永遠。 – Timo 2014-08-04 08:24:12

+2

@Timo:或者你誤解了你的架構師,或者你的架構師需要閱讀http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files,http:// stackoverflow。 com/questions/2095397/jsf-servlet-and-jsp和http://stackoverflow.com/tags/servlets/info之間的區別是什麼如果仍然不確定,請解僱自己並尋找另一個項目。 – BalusC 2014-08-04 08:26:40

+0

這....這應該被標記爲最佳答案! – 2016-10-30 08:16:17