Request Parameters
A request parameter is a parameter passed to a servlet through a request. Request parameters are the result of submitting an HTTP request with a query string that specifies the name/value pairs, or of submitting an HTML form that specifies the name/value pairs. The name and the values are always strings.
The request attribute lives on the request object. As soon as that request is gone, the attribute is gone.
In the example below, we'll perform a POST using HTML and the data will be retrieved by using request.getParameter(). Parameters are Strings, and generally can be retrieved, but not set.
Servlet Definition
package com.swtk.web.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet({ "/SurveyPost", "/post/survey.do" })
public class SurveyPost extends HttpServlet {
private static final long serialVersionUID = 1L;
public SurveyPost() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print(request.getParameter("menuChoice"));
out.close();
}
}
mapped to this location
"/post/survey.do"
HTML Form Definition
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form id="form1" method="post" action="/HelloWorldServlet/post/survey.do">
<select id="menuChoice" name="menuChoice">
<option id="1" value="CA">CA</option>
<option id="2" value="OR">OR</option>
<option id="3" value="AZ">AZ</option>
</select>
<input type="submit" />
</form>
</body>
</html>
deployed to this location in my Web Project:
WebContent/PostExample1.html
Fiddler Output
When I run the HTML page on Tomcat, and hit submit, Fiddler will show this:
POST http://localhost:8080/HelloWorldServlet/post/survey.do HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 13
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/HelloWorldServlet/PostExample1.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fr;q=0.6,nb;q=0.4
menuChoice=OR
Web Output
The Web output shows the attribute value:
No comments:
Post a Comment