iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0
Software Development

從Servlet到Spring MVC系列 第 11

Day10 Servlet - HttpServletRequest and HttpServletResponse

  • 分享至 

  • xImage
  •  

前言

記得我們在day04有提到過,當瀏覽器發送Http request,tomcat接收到http訊息他會將訊息封裝為HttpServletRequest物件與準備回應的物件HttpServletResponse,在透過調用service方法將物件傳入,今天我們就來看看這兩個物件有哪些好用的api吧
https://ithelp.ithome.com.tw/upload/images/20240925/20128084PzSTlc9oqs.png

0、創建module

請參考Day05創建module

HttpServletRequest

我們根據request message的形式分成3個部份來介紹並分別demo,相關api就字面上就可以理解,故不再多贅述

request line api

request hededr api

以下將demo這兩個部份的api

@WebServlet("/DemoHttpRequestApi")
public class DemoHttpRequest extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        res.setContentType("text/plain;charset=UTF-8");
        PrintWriter writer = res.getWriter();

        // request line api
        writer.println("====request line info====");
        writer.println("getMethod: " + req.getMethod());//請求方法
        writer.println("getScheme: " + req.getScheme());//協定
        writer.println("getRequestURI: " + req.getRequestURI());//統一資源標示符
        writer.println("getRequestURL: " + req.getRequestURL());//統一資源定位(地址)
        writer.println("getLocalPort: " + req.getLocalPort());
        writer.println("getServerport: " + req.getServerPort());
        writer.println("getRemotePort: " + req.getRemotePort());

        //request header
        writer.println("====request header info====");
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            writer.println(headerName + ": " + req.getHeader(headerName));
        }

    }
}

https://ithelp.ithome.com.tw/upload/images/20240925/20128084zMxu2L1bu5.png

request parameter api

處理key-value的請求參數
@WebServlet("/HandleUserInfo")
public class DemoHttpRequestUserInfo extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/plain;charset=UTF-8");
        PrintWriter writer = res.getWriter();
        //request parameter
        writer.println("====request param info====");
        writer.println("getParameter username:"+req.getParameter("username"));
        String[] interests = req.getParameterValues("interests");
        for (String interest : interests) {
            writer.println(interest);
        }
        writer.println("====request param info get all ====");
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = req.getParameter(name);
            writer.println(name+":"+value);
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>個人資訊表單</title>
</head>
<body>
<h1>個人資訊表單</h1>
<form action="HandleUserInfo" method="get">
    <!-- 姓名 -->
    <label for="username">姓名:</label>
    <input type="text" id="username" name="username" required><br><br>

    <!-- 電子郵件 -->
    <label for="email">電子郵件:</label>
    <input type="email" id="email" name="email" required><br><br>

    <!-- 電話號碼 -->
    <label for="phone">電話號碼:</label>
    <input type="tel" id="phone" name="phone" pattern="[0-9]{4}-[0-9]{6}"><br><br>

    <!-- 性別 -->
    <label>性別:</label>
    <input type="radio" id="male" name="gender" value="male">
    <label for="male">男</label>
    <input type="radio" id="female" name="gender" value="female">
    <label for="female">女</label><br><br>

    <!-- 出生日期 -->
    <label for="dob">出生日期:</label>
    <input type="date" id="dob" name="dob"><br><br>

    <!-- 地址 -->
    <label for="address">地址:</label>
    <textarea id="address" name="address" rows="4" cols="50"></textarea><br><br>

    <!-- 興趣 -->
    <label>興趣:</label><br>
    <input type="checkbox" id="reading" name="interests" value="reading">
    <label for="reading">閱讀</label><br>
    <input type="checkbox" id="traveling" name="interests" value="traveling">
    <label for="traveling">旅行</label><br>
    <input type="checkbox" id="sports" name="interests" value="sports">
    <label for="sports">運動</label><br>
    <input type="checkbox" id="cooking" name="interests" value="cooking">
    <label for="cooking">烹飪</label><br>
    <input type="checkbox" id="music" name="interests" value="music">
    <label for="music">音樂</label><br><br>

    <!-- 提交按鈕 -->
    <input type="submit" value="提交">
</form>
</body>
</html>

get請求時資訊會夾在url上
https://ithelp.ithome.com.tw/upload/images/20240925/20128084JSXOrQxIx0.png
post method(請自行更換form method為post),請求時的訊息資訊不會在url呈現,會被放置在payload(請求體)之中
https://ithelp.ithome.com.tw/upload/images/20240925/201280842SZoRXHfV0.png

處理request body為json與file的方式

other api

  • ServletContext getServletContext();
    取得ServletContext物件
  • Cookie[] getCookies();
  • HttpSession getSession();
  • void setCharacterEncoding(String encoding) ;

HttpServletResponse

我們根據response message的形式分成3個部份來介紹並分別demo,相關api就字面上就可以理解,故不再多贅述

public class DemoHttpResponse extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        //response line
        res.setStatus(HttpServletResponse.SC_OK);
        
        //response header
        res.setHeader("aaa","bbb");
        //res.setHeader("Content-Type", "text/pain;charset=UTF-8");
        //content-type api
        res.setContentType("text/pain;charset=UTF-8");
        //res.setHeader("content-length", "888");
        //content-length api
        String msg = "Hello DemoHttpResponse";
        res.setContentLength(msg.getBytes(StandardCharsets.UTF_8).length);

        //response body
        PrintWriter writer = res.getWriter();
        writer.println(msg);
    }
}

demo response 設置結果
https://ithelp.ithome.com.tw/upload/images/20240925/20128084M3nFJL2iuq.png

Common MIME types

MIME Type用來告訴瀏覽器該如何解析收到的訊息或是向Web Server告知傳送的數據類型

Extension MIME Type
.html,.htm text/html
.js text/javascript
.css text/css
.json application/json
.csv text/csv
.png image/png
.pdf application/pdf
.xml application/xml
.zip application/zip

Reference


上一篇
Day09 Servlet - ServletContext API
下一篇
Day11 Servlet - RequestDispatcher and SendRedirect
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言