Getting a Request Parameter in a Servlet

In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters – – p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request. This example demonstrates how to get the value of a request parameter in either a GET or POST request.
// See also The Quintessential Servlet

// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

// This method is called by the servlet container to process a POST request.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

// This method handles both GET and POST requests.
private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the value of a request parameter; the name is case-sensitive
    String name = "param";
    String value = req.getParameter(name);
    if (value == null) {
        // The request parameter 'param' was not present in the query string
        // e.g. http://hostname.com?a=b
    } else if ("".equals(value)) {
        // The request parameter 'param' was present in the query string but has no value
        // e.g. http://hostname.com?param=&a=b
    }

    // The following generates a page showing all the request parameters
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // Get the values of all request parameters
    Enumeration enum = req.getParameterNames();
    for (; enum.hasMoreElements(); ) {
        // Get the name of the request parameter
        name = (String)enum.nextElement();
        out.println(name);

        // Get the value of the request parameter
        value = req.getParameter(name);

        // If the request parameter can appear more than once in the query string, get all values
        String[] values = req.getParameterValues(name);

        for (int i=0; i<values.length; i++) {
            out.println("    "+values[i]);
        }
    }
    out.close();
}

Comments

19 Jul 2010 - 10:11pm by Anonymous (not verified)

good example

30 Nov 2010 - 4:12am by Anonymous (not verified)

How to use (call) this in a java programme?

15 Jun 2011 - 12:46am by coach canada (not verified)

It is a fine day. Mum said to me:"Get coach purses please!And look out of the window. What a fine day! Let’s go to park,"It was really a good day, So my mother, my classmate and I went to the park. On the way to the park. I saw coach bags the blue sky with snow-white clouds. Below the trees, there are several kinds of flowers. It’s colorful, blue, red, yellow, pink, purple, orange and white. I saw some coach Madison collection balloons and butterflies in the sky. I ate popcorn, cornflakes, banana and lollipop. They were wonderful. In the afternoon, we went to coach canada store. I visited the birds, mice, cats, dogs, budgies, hamsters, rabbits and so on.

22 Sep 2011 - 1:43am by cheap moncler jackets (not verified)

The important factorscheap moncler jackets why is usually this so? It's very primarily because, you couldcheap moncler jackets locate many monclers moncler jackets outlet comes with ridiculous themes.

27 Sep 2011 - 8:41pm by uggs on sale uk (not verified)

These cheap uggs would be nice investments for you in long term. These uggs sale uk are brilliant and prove to be wonderful for you while it makes you stand out of the crowd. In this modern and fashionable society, people are pursuing for cheap ugg boots uk cool, unique, stylish and innovative. Whether it is Ugg Boots UK or fashion accessories all means a lot for modern society of today. Same is the case with trendy looking ugg boot for sale. When these are ugg sale uk, the excitement just gets doubled. Most chic looking moncler jackets are in fashion now. These are one of the favorite fashion accessories for men and women long time ago. If you have not yet tried moncler outlet, it's time to own one and feel the difference it can make to your personality. These are just brilliant and fabulous moncler online. They are most iconic and can provide you with a new feeling and enhance confidence. The quality of moncler coats is just superior to what you have dreamt of. Today owning a new and trendy looking ugg sale uk are not only meant for the wealthy people. These are now made luxurious and affordable ugg boot sale uk to reach out to every budget and range. You can just enjoy them by ordering discount uggs online where you get the complete satisfaction and genuine quality at best possible rates. The finish, quality and designs you get from Ugg Boots sale are really astonishing and you will love them all.

11 Nov 2011 - 7:45pm by Coach Outlet Online (not verified)

Because

Coach Factory Outlet

the Cain

Coach Factory Store

campaign’s

Coach Outlet

core staff

Coach Outlet

members are

Coach Outlet Online

veterans of

Coach Outlet

Americans for

Coach Outlet Online

Prosperity — Mr. Block,

Chanel Outlet

his deputy

Chanel Outlet

manager, the

Louis Vuitton Outlet

senior

Coach Factory Store

economic adviser —

Chanel Handbags

some critics

Coach Outlet

on the left

Louis Vuitton

suggest that

LV Outlet

despite Mr.

Coach Outlet

Cain’s image as

Coach Outlet

an outsider, his candidacy

Coach Outlet

is in effect a mouthpiece for the

Chanel Bags

corporate interests of

Coach Outlet

the Koch brothers.

30 Nov 2011 - 3:15pm by Anonymous (not verified)

fittaymu!

12 Mar 2012 - 1:34am by Cheap New Era Hats (not verified)

Welcome to Cheap New Era Caps Shop!We offer wholesale cheap new era caps,New Era 59fifty Caps,New Era Snapback Caps,Wholesale New Era Caps,Wholesale New Era Fitted Caps. Fast shipping, free tax,lowest price,authentic quality!

15 May 2012 - 5:59pm by adidas jeremy scott shoes (not verified)

didas follows the growing number of other brands that have already established presence in the virtual world: Scion and Starwood are Adidas Porsche Design Bounce the most recent additions, and American Apparel has set up its own Adidas Porsche Bounce S boutique earlier this year.The interior is spacious and is built to accommodate convenient camera controls.There are no attendants behind the counters and you buy the shoes by clicking on Adidas Porsche Bounce S2 one of the boxes and paying 50 linden dollars (about 20 real-world cents).The store sits on a private island away from the Second Life�s mainland.Adidas Opens Store in Second Life�Men's Adidas Campus Series With the increasingly fierce competition in business, industry marketing activities and more frequent, the greater efforts.The site has a store locator feature Adidas Porsche Bounce SL and it would have been a nice nod to the Second Life�s fan base if it had mentioned the Second Life outlet.The video screens on the sides play the same promo spot and invite visitors to check out the Adidas campaign site What�s Next.Unlike the American Apparel store, Adidas here sells only one SKU � the a3 that comes either in white or red Adidas Porsche Design Golf and black styles.Besides the store itself, the Adidas complex includes a dome that projects a branded video clip, a few billboard installations, and an orange �testing area� trampoline to demonstrate the shoes� �bouncy� positioning.Adidas opened a store in Second Life last week to promote its a3 Microride sneakers.

16 May 2012 - 12:00am by adidas jeremy scott shoes (not verified)

They provide a spring heel motion, which prevents the runner from hurting his/her back and also offer an aerodynamic shape so as to allow the runner better grip and control of the surface.Adidas tennis shoes are designed keeping the sideways cut of the player in mind.Adidas brings forth a revolution in sports wear and offers you a chance to welcome health back into your life.When playing a game or joining a gym, one of the first things to look into is right footwear.They have what is known as non-marking soles, commonly called yellow soles.

They are a bit expensive than usual sports footwear and restricted to the courts only.While these electronics are welcome, they have taken away the element of exercise from our lives.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.