iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
自我挑戰組

從0開始學習Java系列 第 18

Servlet實作doGet() 和 doPost() 方法

  • 分享至 

  • xImage
  •  
  1. 建立 Servlet
package web.test.servlet;

import java.io.IOException;
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 的路徑為 /hello
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String name = req.getParameter("name");
        resp.setContentType("text/html; charset=UTF-8");
        resp.getWriter().println("<h2>GET 請求結果</h2>");
        resp.getWriter().println("你好, " + name + " (來自 doGet)");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String name = req.getParameter("name");
        resp.setContentType("text/html; charset=UTF-8");
        resp.getWriter().println("<h2>POST 請求結果</h2>");
        resp.getWriter().println("你好, " + name + " (來自 doPost)");
    }
}

  1. 建立 index.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>Servlet GET/POST 範例</title>
</head>
<body>
    <h1>Servlet GET / POST 測試</h1>

    <!-- GET 請求 -->
    <h2>GET 請求</h2>
    <form action="hello" method="get">
        姓名:<input type="text" name="name">
        <button type="submit">送出 GET</button>
    </form>

    <!-- POST 請求 -->
    <h2>POST 請求</h2>
    <form action="hello" method="post">
        姓名:<input type="text" name="name">
        <button type="submit">送出 POST</button>
    </form>
</body>
</html>


上一篇
web.xml檔案內容
下一篇
Google Gson
系列文
從0開始學習Java21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言