Suppose the following HTML code is used to enter user information and call the servlet url-pattern “Record”:

4 phương ánCó giải thích
Đề bài
<html>
  <body>
    <form action="Record" >
      User:<input type="text" id="txtname1"  name="txtname2">
      <br>
        Address:<input type="text" id="txtadd1"  name="txtadd2">
        <br>
          <input type="submit" value="GotoZone">
          </form>
        </body>
      </html>

Which of the Servlet code takes input from an html form and displays it on the browser?

Các phương án trả lời

Chọn một phương án
Lời giảiChọn phương án để mở

Đáp án đúng: "public class RecordServlet extends HttpServlet

Lời giải
{
    protected void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
        {
                PrintWriter pw=res.getWriter();
                res.setContentType("text/html");
                String account=req.getParameter("txtname2");
                String Addr=req.getParameter("txtadd2");
                pw.println("Hello " + account + " from" + Addr);
                pw.close();

        }

}". Biểu mẫu khai thuộc tính action trỏ tới Record mà không ghi method, nên trình duyệt gửi theo mặc định là GET, vì vậy lớp servlet phải cài phương thức doGet; đồng thời tên tham số gửi đi là giá trị của thuộc tính name chứ không phải id, tức txtname2 và txtadd2. Lựa chọn dùng "doPost(HttpServletRequest req,HttpServletResponse res)" cùng "req.getParameter("txtname1")" sai cả hai chỗ: không cài doGet nên yêu cầu từ biểu mẫu bị báo không hỗ trợ phương thức, mà tên id cũng không bao giờ được gửi lên. Lựa chọn đọc đúng "req.getParameter("txtname2")" nhưng lại đặt mã trong "doPost(HttpServletRequest req,HttpServletResponse res)" thì vẫn không chạy với yêu cầu GET. Lựa chọn có đúng "doGet(HttpServletRequest req,HttpServletResponse res)" lại lấy "req.getParameter("txtadd1")" theo id, nên hai biến nhận về null và trang chỉ in ra chữ Hello kèm null.

Cùng phần 2

Xuất hiện trong 1 bộ đề