2015-12-17 33 views
2

假設我有一些form這樣檢索值

<form action="/add_scores" method="post" enctype="multipart/form-data" id="add_link_form"> 
    <input type="text" name="subject" id="subject" placeholder="subject"> 
    <input type="text" name="link" id="link"> 
    <button type="submit" class="btn btn-success">Add</button> 
</form> 

在我servlet

@Override 
public void doPost(HttpServletRequest req, HttpServletResponse res) 
     throws ServletException, IOException { 
    String subject = (String)req.getAttribute("subject"); 
    String link = (String)req.getAttribute("link"); 
} 

subjectlink總是null當我張貼的東西。但如果我在表格中使用method="get"並將doPost重命名爲doGet,此代碼正常工作,並且subjectlink都不錯。 (如果我將getAttribute()更改爲getParameter(),也會發生這種情況)。

爲什麼會發生這種情況,我怎樣才能得到我的值在doPost

+0

@Pshemo我使用谷歌應用程序引擎 – PepeHands

+0

老實說,我是新來的JavaEE和我從來沒有使用過該平臺。但只是爲了確保我正確理解你的問題,你聲稱''getGet''具有'getAttribute'可以正常工作,但帶有'getAttribute'的'doPost'不是,你問的原因是什麼? (無論如何,閱讀''*參數*的正確方法是在'do ...'方法中使用'getParameter'而不是'getAttribute')。 – Pshemo

+0

@Pshemo是的。我在'do'方法中都使用'getParameter'和'getAttribute'。它在'doGet'中工作,但不在'doPost'中。 – PepeHands

回答

1

根據Difference between getAttribute() and getParameter(),您應該使用getParameter而不是getAttribute;根據http://www.w3.org/TR/html401/interact/forms.html,您的表單應該使用enctype="application/x-www-form-urlencoded" - 多部分編碼類型用於上傳文件的表單。順便說一句,這兩個問題都不依賴於您是否使用App Engine或其他Web服務器。

+0

對不起,愚蠢的問題(我沒有太多的經驗,在現實世界的網頁開發),但不'應用程序/ x-www-form-urlencoded'默認enctype?如果是,那麼根據我之前評論中的建議刪除'enctype'應該糾正這個問題,但是OP聲稱他仍然無法使用'getProperty'接收正確的數據。 – Pshemo

+0

@Pshemo,是的,這確實是enctype的默認值(根據我指出的w3.org文檔) - 我只是認爲「顯式比隱式更好」。我無法複製OP報告的特定症狀,所以我想象,在99.4%的這種情況下,他實際上並未嘗試所有組合(getParameter和適當的enctype)。 –

0

試試這個:

@Override 
public void doPost(HttpServletRequest req, HttpServletResponse res) 
     throws ServletException, IOException { 
    String subject = req.getParameter("subject"); 
    String link = req.getParameter("link"); 
}