<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorGetServlet.java is shown in the following listing. The doGet( )
method is overridden to process any HTTP GET requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made
by the user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is:  ");
pw.println(color);
pw.close();
}
}
Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml
file, as previously described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that
is sent to the web server. Assume that the user selects the red option and submits the form.
The URL sent from the browser to the server is
http://localhost:8080/servlets-examples/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home