實作步驟概覽
- 建立 Web 專案與 Servlet
- 配置
web.xml 或使用 @WebServlet 註解
- 編寫 JSP 表單頁面
- 部署至 Tomcat 並驗證
1. Servlet 實作 (LoginServlet.java)
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 獲取參數(GET 參數在 URL 查詢字串中)
String username = req.getParameter("username");
String password = req.getParameter("password");
// 2. 處理中文編碼(Tomcat 8+ 預設 UTF-8,舊版需手動轉碼)
// username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
// 3. 業務邏輯驗證
boolean success = "admin".equals(username) && "123456".equals(password);
// 4. 回應結果
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println(success ? "登入成功,歡迎 " + username : "登入失敗:帳號或密碼錯誤");
}
}
2. JSP 表單頁面 (login.jsp)
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h2>用戶登入</h2>
<form action="login" method="get">
用戶名:<input type="text" name="username" required><br>
密碼:<input type="password" name="password" required><br>
<input type="submit" value="登入">
</form>
</body>
</html>
3. 部署與驗證
- 將專案打包為 WAR 或直接在 IDE 中配置 Tomcat 部署。
- 啟動 Tomcat,瀏覽器訪問
https://localhost:8080/專案名/login.jsp。
- 輸入帳號
admin、密碼 123456 提交,觀察瀏覽器網址列變為 .../login?username=admin&password=123456,頁面顯示「登入成功」。
GET 請求特性與注意事項
- 參數顯示於 URL,不適合傳輸敏感資料(密碼、Token)。
- URL 長度限制(約 2KB),不適合大量資料。
- 瀏覽器會緩存 GET 請求,相同 URL 可能不發送請求直接讀取緩存。
- 僅支援 ASCII 字元,中文需 URL 編碼(瀏覽器自動處理)。
- 安全建議:生產環境登入、修改資料務必使用 POST 並配合 HTTPS。