簡體   English   中英

編寫一個簡單的servlet。 通過Servlet獲取和發送數據

[英]Writing a simple servlet. Getting and sending data via servlet

我是servlet編寫的新手。 我需要編寫一個簡單的servlet,它必須通過表單輸入和輸出數據。 例如,在我的servlet中,我輸入有關某些汽車的數據(它由以下屬性組成:汽車名稱,汽車尺寸和汽車顏色)。 Servlet必須保存這些數據。 而且,它必須顯示保存的數據。 我已經完成了servlet的操作,但是我仍然不知道要完成它。

這是頁面的html代碼,從中調用servlet:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cars</title>
</head>

<body><center>Cars</center>

<p>Name: </p>
<form id="form1" name="form1" method="post" action="">
  <label for="car_name"></label>
  <input type="text" name="car_name" id="car_name" />
</form>
<p>Color: </p>
<form id="form2" name="form2" method="post" action="">
  <label for="car_name"></label>
  <input type="text" name="car_color" id="car_color" />
</form>
<p>Size: </p>
<form id="form3" name="form3" method="post" action="">
  <label for="car_size"></label>
  <input type="text" name="car_size" id="car_size" />
</form>
<input name="send" type="button" value="Send" />
<input name="get_out" type="button" value="Output" />
<textarea name="output" cols="10" rows="10" readonly="readonly"></textarea>
<fieldset>
<legend>Testing Simple Servlets</legend>
<ul>
  <li><a href="carServlet">carServlet</a> The carServlet is a servlet that
      gets and posts cars' attributes data</li>
</ul>
</fieldset>
</body>
</html>

這是一個servlet代碼(java),(我才開始意識到它):

package testPackage;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet("/carServlet")
public class CarServlet extends HttpServlet 
{
    //Some code strings which finds items on the web-page
    //Only for example: String item = (String)getItem("car_name");
}

如何完成它以便servlet可以保存並打印出保存的數據?

package testPackage;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet("/carServlet")
public class CarServlet extends HttpServlet 
{
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
   }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String carName = request.getParameter("car_name");
        System.out.println("Car Name:" + carName);
   }
}

嘗試使用此方法在Servlet中實現doGet和doPost方法。 您正在通過郵寄方式提交表單,因此可以將代碼放在此處。 我只是將get轉發給了post方法。 您可以通過request.getParameter(“ parameterName”);訪問參數。

HREF鏈接->您可以在Servlet的doGet方法中獲取數據。 FORM提交->查看您的doPost方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM