|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Get Request Parameters in a Servlet
This example shows how to get the parameters sent in a http request to a servlet. In this example we use the method service() which will process requests of type GET as well as requests of type POST. To get the parameter names the method getParameterNames() is called on the request object. The method returns an Enumeration which we use to loop through the parameter names, and for each name the method getParameter() is called on the request object to get the value of that parameter. |
import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; /** * Example Servlet * @author www.javadb.com */ public class ExampleServlet extends HttpServlet { /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); printPageStart(out); Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); out.println(paramName + " = " + request.getParameter(paramName) + "<br/>"); } printPageEnd(out); } /** Prints out the start of the html page * @param out the PrintWriter object */ private void printPageStart(PrintWriter out) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ExampleServlet</title>"); out.println("</head>"); out.println("<body>"); } /** Prints out the end of the html page * @param out the PrintWriter object */ private void printPageEnd(PrintWriter out) { out.println("</body>"); out.println("</html>"); out.close(); } } |
So, if the http request looked like this in the browser (assuming we run the servlet on our own computer): |
http://localhost/ExampleServlet?color1=blue&color2=red |
The output to the page would be: |
color1 = blue color2 = red |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
