出于好奇,我发送的get和post参数具有相同的名称和不同的值。
JSP:
<form action="actionName?param1=value1" method="post">
<input type="text" value="value2" name="param1" id="param1">
<input type="submit" value="Submit">
</form>
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String strParam1 = request.getParameter("param1");
}
我总是将strParam1的值变为&#34; value1&#34;。
那么,这是否意味着获取参数对post参数的重要性还是取决于?
答案 0 :(得分:0)
获取和发布显然处理方式不同。令人困惑,因为我看到许多以与获取请求相同的方式处理帖子提交的例子。
以下文章深入探讨了这一点。
doPost方法使用getParameterNames和getParameterValues 获取表单数据的方法。
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// first, set the "content type" header of the response
res.setContentType("text/html");
//Get the response's PrintWriter to return text to the client.
PrintWriter toClient = res.getWriter();
try {
//Open the file for writing the survey results.
String surveyName = req.getParameterValues("survey")[0];
FileWriter resultsFile = new FileWriter(resultsDir
+ System.getProperty("file.separator")
+ surveyName + ".txt", true);
PrintWriter toFile = new PrintWriter(resultsFile);
// Get client's form data & store it in the file
toFile.println("<BEGIN>");
Enumeration values = req.getParameterNames();
while(values.hasMoreElements()) {
String name = (String)values.nextElement();
String value = req.getParameterValues(name)[0];
if(name.compareTo("submit") != 0) {
toFile.println(name + ": " + value);
}
}
toFile.println("<END>");
//Close the file.
resultsFile.close();
// Respond to client with a thank you
toClient.println("<html>");
toClient.println("<title>Thank you!</title>");
toClient.println("Thank you for participating");
toClient.println("</html>");
} catch(IOException e) {
e.printStackTrace();
toClient.println(
"A problem occured while recording your answers. "
+ "Please try again.");
}
// Close the writer; the response is done.
toClient.close();
}