[英]servlet, tracking session with hidden parameters
我在servlet編碼方面遇到麻煩,但不知道如何解決。 我試圖僅使用隱藏參數來跟蹤會話(使用TomCat Web服務器)。 在此示例中,有名稱,姓氏和電子郵件作為參數。 我的想法是每次僅詢問客戶一個參數,並將其作為隱藏參數發送給他(迭代)。
如果我僅啟動一個會話(因為從客戶端發送第一個參數到客戶端發送最后一個參數),我的servlet就可以正常工作。 問題是,當我開始另一個會話時:當我向服務器發送該姓氏(與上一個會話不同的值)時,服務器會給我一個URL,其中隱藏參數“ surname”是當前姓氏的兩倍以及前一個會話的姓氏的值。
這是我的servlet類:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class HiddenParamServlet extends HttpServlet {
private final String[] PARAMS = { "name", "surname", "e-mail" };
private Map<String, String> hiddenParameters;
@Override
public void init() {
hiddenParameters = new HashMap<String, String>();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// control the last parameter added by the client
List<String> clientParameters = Collections.list(request.getParameterNames());
// checks if the client already sent all the parameters
if(clientParameters.size() == 3) {
// start the html document
out.println("<html><head><title>Session finished</title></head>");
out.println("<body><h1>Session succesfully completed</h1></body>");
out.println("</html>");
// end the html
out.close();
hiddenParameters.clear();
}
else {
String lastParam = clientParameters.get(clientParameters.size() -1);
//memorizing the last param sent by the client
String value = request.getParameter(lastParam);
hiddenParameters.put(lastParam, value);
// starts the HTML document
out.println("<html>");
out.println("<head><title>Tracking session with hidden parameters</title></head>");
out.println("<body>");
out.println("<form method=\"get\" action=\"/DirectoryDiSaluto/HiddenParamServlet\">");
out.println("<p>");
//write the next parameter to ask to the client
out.println("<label>Insert "+PARAMS[clientParameters.size()]+":");
// write the hidden parameters of the server
for(String key : hiddenParameters.keySet()) {
out.println("<input type=\"hidden\" name=\""
+key+"\" value=\""+hiddenParameters.get(key)+"\" />");
}
out.println("<input type=\"text\" name=\""+PARAMS[clientParameters.size()]+"\" />");
out.println("<input type=\"submit\" value=\"Submit\" />");
out.println("</label>");
out.println("</p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
// end the html
out.close();
}
}
}
這是所有開始的html頁面:
<html>
<head>
<title>Tracking session with hidden parameters</title>
</head>
<body>
<form method="get" action="/DirectoryDiSaluto/HiddenParamServlet">
<p>
<label>Insert name:
<input type="text" name="name"/>
<input type="submit" value="Submit" />
</label>
</p>
</form>
</body>
</html>
我不明白問題出在哪里。 你能幫助我嗎? 非常感謝!
hiddenParameters的行為不正確,因為它的范圍很廣。 請查看此答案以獲取更多說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.