Servlet使用注釋


注釋表示後設資料。 如果使用注釋,則不需要部署描述符(web.xml檔案)。但是應該在tomcat7以上版本中部署執行,tomcat7之前的版本是不支援註解的。 @WebServlet注釋用於將servlet對映到指定的名稱,這是Servlet3的特性,所以在建立專案時要指定Servlet的版本為3.0以上。

在前面幾個專案範例中,我們已經使用過了 @WebServlet注釋,如:

使用註釋的簡單servlet範例

這個範例中演示如何使用帶有注釋的servlet。

開啟Eclipse,建立一個動態Web專案:ServletWithAnnotation,其完整的目錄結構如下所示 -

注意:建立專案選擇Dynamic web module version的版本是:3.0以上。

以下是這個專案中的幾個主要的程式碼檔案。

檔案:index.html -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Servlet註解實現模式</title>
</head>
<body>
    <div style="text-align:center;">
        <a href="Simple">檢視Servlet註解範例</a>
    </div>
</body>
</html>

檔案:Sample.java -

package com.yiibai;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Simple
 */
@WebServlet("/Simple")
public class Simple extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        out.print("<html><body>");
        out.print("<div style='text-align:center;'><h3>Hello Servlet</h3>");
        out.print("<p>這是使用Servlet註解實現模式URL對映的組態範例</p></div>");
        out.print("</body></html>");
    }
}

注意: 不需要組態web.xml

在編寫上面程式碼後,部署此Web應用程式(在專案名稱上點選右鍵->」Run On Server…」),開啟瀏覽器存取URL: http://localhost:8080/ServletWithAnnotation/ ,如果沒有錯誤,應該會看到以下結果 -

點選連結,顯示結果如下 -