基本上,我正在處理的這個頁面的目標是讓用戶輸入股票代碼,並將此信息發送到post方法並將數據發送回放在相同的html/jsp頁面上。我已經能夠在表單導向另一個JSP頁面的情況下工作,但這必須是一個單獨的頁面,我希望能夠保持在同一頁面上並讓信息出現。如果你有一個資源可以教我如何處理這個問題,那麼我會很感激,就像解決方案一樣。我一直在使用Gradle構建工具。如何從post servlet接收信息以放入HTML/JSP
這裏是(在index.jsp中)的形式爲:
<h1>Search Stock</h1>
<form method="POST" action="DataPage.jsp">
<input type = "text" name = "Symbol">
<input type = "submit" name = "getData">
</form>
這裏是起作用JSP代碼(DataPage.jsp):
<%
String Ticker = request.getParameter("Symbol");
PrintWriter write = response.getWriter();
if((Ticker == null)){
String message = "Please enter a stock symbol";
write.println(message);
}else{
try{
Company object = Serializing.getCompany(Ticker);
object.updateData();
write.println("data last added" + object.getLastUpdate());
write.println(object.getSentiment());
}catch(NullPointerException x){
Company object = Serializing.getCompany(Ticker);
}
}%>
這裏是我試圖寫的servlet(DataServlet .java),我幾乎沒有使用servlets的經驗,我從不同的來源和關於計算器的問題找到了這個問題:
package Default;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ceyer on 9/3/2015.
*/
@javax.servlet.annotation.WebServlet(name = "DataServlet", urlPatterns = ("/"))
public class DataServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public DataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String Ticker = request.getParameter("Symbol");
if ((Ticker == null)||Ticker.trim().isEmpty()) {
String message = "Please enter a stock symbol";
request.setAttribute("data", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else {
PrintWriter write = response.getWriter();
try {
Company object = Serializing.getCompany(Ticker);
object.updateData();
request.setAttribute("data", object.getSentiment() + "updated last" + object.getLastUpdate());
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (NullPointerException x) {
Company object = Serializing.getCompany(Ticker);
request.setAttribute("data", "We do not have info on this stock");
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
你爲什麼不使用AJAX? –