How do I get parameter names from servlet request?

This example show you how to obtain parameter name from servlet request. By calling request.getParameterNames() you will get an Enumeration object by iterating this object you can get the parameter names.

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

@WebServlet(name = "ParameterName", urlPatterns = "/parameter-names")
public class ParameterName extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter pw = response.getWriter();

        // Let's obtains parameters name here!
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String parameterName = enumeration.nextElement();
            pw.println("Parameter = " + parameterName);
        }
        pw.close();
    }
}

When you call the servlet and pass some parameters you get the parameter name echoed on the web browser.

http://localhost:8080/parameter-names?txid=001&item=10&price=1000

Parameter = txid
Parameter = item
Parameter = price

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I read request parameter from servlet?

When creating an application with Java servlet most of the time we will work with the request and response object. From the request object we can read the parameter submitted by the user’s browser either through an HTTP GET or POST method.

Basically what you need to know is when you try to get the passed parameter from inside the servlet you can call the request.getParameter(paramName) where the paramName is the name of parameter that you want to read from the servlet request object.

In this example I’ll show you how to read the parameter to process user action in a very simple login servlet. In this example we’ll create a login form, a JSP page that accept user input for a username and password.

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login Page</title>
</head>
<body>
<form id="loginForm" action="${pageContext.request.contextPath}/login" method="post">
    <label for="username">Username</label>
    <input id="username" type="text" name="username"/>
    <label for="password">Password</label>
    <input id="password" type="password" name="password"/>
    <input type="submit" value="Login"/>
</form>
</body>
</html>

In this form you’ll have to input box for a username and password. You also have a submit button for executing the login process. Now we have the form, let’s create the login servlet.

package org.kodejava.servlet;

import javax.servlet.Servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet implements Servlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        doLogin(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        doLogin(request, response);
    }

    protected void doLogin(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        // Here we read the parameters from servlet request
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        PrintWriter pw = response.getWriter();
        if (username != null && username.equals("administrator")
                && password != null && password.equals("secret")) {
            // authentication accepted!
            pw.println("Success!");
        } else {
            // authentication denied!
            pw.println("Denied!");
        }
        pw.close();
    }
}   

Now you have everything, you can deploy the application on your servlet container, for example Apache Tomcat. Access your login page in the following address:

http://localhost:8080/login.jsp

You can also access the servlet directly from the following url:

http://localhost:8080/login

To pass the username and password information you can append the parameter like:

http://localhost:8080/login?username=administrator&password=secret

This will call the servlet and validate your login information.

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I get a list of country names?

Using the code below you can get a list of country names and its ISO code by using the locale class implementation in Java.

package org.kodejava.util;

import java.text.Collator;
import java.util.*;

public class CountryList {
    public static void main(String[] args) {
        // A collection to store our country object
        List<Country> countries = new ArrayList<>();

        // Get ISO countries, create Country object and
        // store in the collection.
        String[] isoCountries = Locale.getISOCountries();
        for (String country : isoCountries) {
            Locale locale = new Locale("en", country);
            String iso = locale.getISO3Country();
            String code = locale.getCountry();
            String name = locale.getDisplayCountry();

            if (!"".equals(iso) && !"".equals(code) && !"".equals(name)) {
                countries.add(new Country(iso, code, name));
            }
        }

        // Sort the country by their name and then display the content
        // of countries collection object.
        countries.sort(new CountryComparator());

        for (Country country : countries) {
            System.out.println(country);
        }
    }

    /**
     * Country pojo class.
     */
    static class Country {
        private final String iso;
        private final String code;
        private final String name;

        Country(String iso, String code, String name) {
            this.iso = iso;
            this.code = code;
            this.name = name;
        }

        public String toString() {
            return iso + " - " + code + " - " + name.toUpperCase();
        }
    }

    /**
     * CountryComparator class.
     */
    private static class CountryComparator implements Comparator<Country> {
        private final Comparator<Object> comparator;

        CountryComparator() {
            comparator = Collator.getInstance();
        }

        public int compare(Country c1, Country c2) {
            return comparator.compare(c1.name, c2.name);
        }
    }
}

Here are the list of countries we got:

ISO CODE NAME
AFG AF AFGHANISTAN
ALA AX Ă…LAND ISLANDS
ALB AL ALBANIA
DZA DZ ALGERIA
ASM AS AMERICAN SAMOA
AND AD ANDORRA
AGO AO ANGOLA
AIA AI ANGUILLA
ATA AQ ANTARCTICA
ATG AG ANTIGUA AND BARBUDA
ARG AR ARGENTINA
ARM AM ARMENIA
ABW AW ARUBA
AUS AU AUSTRALIA
AUT AT AUSTRIA
AZE AZ AZERBAIJAN
BHS BS BAHAMAS
BHR BH BAHRAIN
BGD BD BANGLADESH
BRB BB BARBADOS
BLR BY BELARUS
BEL BE BELGIUM
BLZ BZ BELIZE
BEN BJ BENIN
BMU BM BERMUDA
BTN BT BHUTAN
BOL BO BOLIVIA
BES BQ BONAIRE, SINT EUSTATIUS AND SABA
BIH BA BOSNIA AND HERZEGOVINA
BWA BW BOTSWANA
BVT BV BOUVET ISLAND
BRA BR BRAZIL
IOT IO BRITISH INDIAN OCEAN TERRITORY
VGB VG BRITISH VIRGIN ISLANDS
BRN BN BRUNEI
BGR BG BULGARIA
BFA BF BURKINA FASO
BDI BI BURUNDI
KHM KH CAMBODIA
CMR CM CAMEROON
CAN CA CANADA
CPV CV CAPE VERDE
CYM KY CAYMAN ISLANDS
CAF CF CENTRAL AFRICAN REPUBLIC
TCD TD CHAD
CHL CL CHILE
CHN CN CHINA
CXR CX CHRISTMAS ISLAND
CCK CC COCOS ISLANDS
COL CO COLOMBIA
COM KM COMOROS
COG CG CONGO
COK CK COOK ISLANDS
CRI CR COSTA RICA
CIV CI CĂ”TE D’IVOIRE
HRV HR CROATIA
CUB CU CUBA
CUW CW CURAÇAO
CYP CY CYPRUS
CZE CZ CZECH REPUBLIC
DNK DK DENMARK
DJI DJ DJIBOUTI
DMA DM DOMINICA
DOM DO DOMINICAN REPUBLIC
ECU EC ECUADOR
EGY EG EGYPT
SLV SV EL SALVADOR
GNQ GQ EQUATORIAL GUINEA
ERI ER ERITREA
EST EE ESTONIA
ETH ET ETHIOPIA
FLK FK FALKLAND ISLANDS
FRO FO FAROE ISLANDS
FJI FJ FIJI
FIN FI FINLAND
FRA FR FRANCE
GUF GF FRENCH GUIANA
PYF PF FRENCH POLYNESIA
ATF TF FRENCH SOUTHERN TERRITORIES
GAB GA GABON
GMB GM GAMBIA
GEO GE GEORGIA
DEU DE GERMANY
GHA GH GHANA
GIB GI GIBRALTAR
GRC GR GREECE
GRL GL GREENLAND
GRD GD GRENADA
GLP GP GUADELOUPE
GUM GU GUAM
GTM GT GUATEMALA
GGY GG GUERNSEY
GIN GN GUINEA
GNB GW GUINEA-BISSAU
GUY GY GUYANA
HTI HT HAITI
HMD HM HEARD ISLAND AND MCDONALD ISLANDS
HND HN HONDURAS
HKG HK HONG KONG
HUN HU HUNGARY
ISL IS ICELAND
IND IN INDIA
IDN ID INDONESIA
IRN IR IRAN
IRQ IQ IRAQ
IRL IE IRELAND
IMN IM ISLE OF MAN
ISR IL ISRAEL
ITA IT ITALY
JAM JM JAMAICA
JPN JP JAPAN
JEY JE JERSEY
JOR JO JORDAN
KAZ KZ KAZAKHSTAN
KEN KE KENYA
KIR KI KIRIBATI
KWT KW KUWAIT
KGZ KG KYRGYZSTAN
LAO LA LAOS
LVA LV LATVIA
LBN LB LEBANON
LSO LS LESOTHO
LBR LR LIBERIA
LBY LY LIBYA
LIE LI LIECHTENSTEIN
LTU LT LITHUANIA
LUX LU LUXEMBOURG
MAC MO MACAO
MKD MK MACEDONIA
MDG MG MADAGASCAR
MWI MW MALAWI
MYS MY MALAYSIA
MDV MV MALDIVES
MLI ML MALI
MLT MT MALTA
MHL MH MARSHALL ISLANDS
MTQ MQ MARTINIQUE
MRT MR MAURITANIA
MUS MU MAURITIUS
MYT YT MAYOTTE
MEX MX MEXICO
FSM FM MICRONESIA
MDA MD MOLDOVA
MCO MC MONACO
MNG MN MONGOLIA
MNE ME MONTENEGRO
MSR MS MONTSERRAT
MAR MA MOROCCO
MOZ MZ MOZAMBIQUE
MMR MM MYANMAR
NAM NA NAMIBIA
NRU NR NAURU
NPL NP NEPAL
NLD NL NETHERLANDS
ANT AN NETHERLANDS ANTILLES
NCL NC NEW CALEDONIA
NZL NZ NEW ZEALAND
NIC NI NICARAGUA
NER NE NIGER
NGA NG NIGERIA
NIU NU NIUE
NFK NF NORFOLK ISLAND
MNP MP NORTHERN MARIANA ISLANDS
PRK KP NORTH KOREA
NOR NO NORWAY
OMN OM OMAN
PAK PK PAKISTAN
PLW PW PALAU
PSE PS PALESTINE
PAN PA PANAMA
PNG PG PAPUA NEW GUINEA
PRY PY PARAGUAY
PER PE PERU
PHL PH PHILIPPINES
PCN PN PITCAIRN
POL PL POLAND
PRT PT PORTUGAL
PRI PR PUERTO RICO
QAT QA QATAR
REU RE REUNION
ROU RO ROMANIA
RUS RU RUSSIA
RWA RW RWANDA
BLM BL SAINT BARTHÉLEMY
SHN SH SAINT HELENA
KNA KN SAINT KITTS AND NEVIS
LCA LC SAINT LUCIA
MAF MF SAINT MARTIN
SPM PM SAINT PIERRE AND MIQUELON
VCT VC SAINT VINCENT AND THE GRENADINES
WSM WS SAMOA
SMR SM SAN MARINO
STP ST SAO TOME AND PRINCIPE
SAU SA SAUDI ARABIA
SEN SN SENEGAL
SRB RS SERBIA
SYC SC SEYCHELLES
SLE SL SIERRA LEONE
SGP SG SINGAPORE
SXM SX SINT MAARTEN (DUTCH PART)
SVK SK SLOVAKIA
SVN SI SLOVENIA
SLB SB SOLOMON ISLANDS
SOM SO SOMALIA
ZAF ZA SOUTH AFRICA
SGS GS SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS
KOR KR SOUTH KOREA
SSD SS SOUTH SUDAN
ESP ES SPAIN
LKA LK SRI LANKA
SDN SD SUDAN
SUR SR SURINAME
SJM SJ SVALBARD AND JAN MAYEN
SWZ SZ SWAZILAND
SWE SE SWEDEN
CHE CH SWITZERLAND
SYR SY SYRIA
TWN TW TAIWAN
TJK TJ TAJIKISTAN
TZA TZ TANZANIA
THA TH THAILAND
COD CD THE DEMOCRATIC REPUBLIC OF CONGO
TLS TL TIMOR-LESTE
TGO TG TOGO
TKL TK TOKELAU
TON TO TONGA
TTO TT TRINIDAD AND TOBAGO
TUN TN TUNISIA
TUR TR TURKEY
TKM TM TURKMENISTAN
TCA TC TURKS AND CAICOS ISLANDS
TUV TV TUVALU
VIR VI U.S. VIRGIN ISLANDS
UGA UG UGANDA
UKR UA UKRAINE
ARE AE UNITED ARAB EMIRATES
GBR GB UNITED KINGDOM
USA US UNITED STATES
UMI UM UNITED STATES MINOR OUTLYING ISLANDS
URY UY URUGUAY
UZB UZ UZBEKISTAN
VUT VU VANUATU
VAT VA VATICAN
VEN VE VENEZUELA
VNM VN VIETNAM
WLF WF WALLIS AND FUTUNA
ESH EH WESTERN SAHARA
YEM YE YEMEN
ZMB ZM ZAMBIA
ZWE ZW ZIMBABWE

How do I create a hit counter servlet?

Here we have a simple example of creating a hit counter using servlet. The servlet updates the hits counter every time a page is visited and display the number of hits as an image. The image is generated at runtime using Java’s java.awt.Graphic2D and javax.imageio.ImageIO class.

To store the number of visit data we create a table hit_counter with a single field called counter and set the initial value of the counter to zero. Below is the HitCounterServlet servlet code.

package org.kodejava.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.*;

@WebServlet(name = "HitCounterServlet", urlPatterns = "/hitcounter")
public class HitCounterServlet extends HttpServlet {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        updateHitCounter();
        getHitCounterImage(response);
    }

    private void updateHitCounter() {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            // Update the hits counter table by incrementing the
            // counter every time a user hits our page.
            String sql = "UPDATE hit_counter SET counter = counter + 1";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void getHitCounterImage(HttpServletResponse response) throws IOException {
        String hits = "";
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            // Get the current hits counter from database.
            String sql = "SELECT counter FROM hit_counter";
            PreparedStatement stmt = connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                hits = rs.getString("counter");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // Create an image of our counter to be sent to the browser.
        BufferedImage buffer = new BufferedImage(100, 20, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffer.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.setFont(new Font("Roboto", Font.BOLD, 20));
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 100, 30);
        g.setColor(Color.BLACK);
        g.drawString(hits, 0, 20);

        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(buffer, "png", os);
        os.close();
    }
}

To display the hits counter image on the JSP page, create an img tag with the source (src) point to our HitCounterServlet servlet url.

Visited for: <img src="http://localhost:8080/hitcounter" alt="Hit Counter"/> times.

Maven dependencies

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create a HelloWorld Servlet?

Servlet is a Java solution for creating a dynamic web application, it can be compared with the old CGI technology. Using Servlet we can create a web application that can display information from a database, receive information from a web form to be stored in the application database.

This example shows the very basic of servlet, it returns a hello world html document for the browser. At the very minimum a servlet will have a doPost() and doGet() method which handles the HTTP POST and GET request.

package org.kodejava.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "HelloWorldServlet", urlPatterns = {"/hello", "/helloworld"})
public class HelloWorld extends HttpServlet {

    public HelloWorld() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        doPost(req, res);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
        res.setContentType("text/html");

        PrintWriter writer = res.getWriter();
        writer.println("<html>");
        writer.println("<head><title>Hello World Servlet</title></head>");
        writer.println("<body>Hello World! How are you doing?</body>");
        writer.println("</html>");
        writer.close();
    }
}

When the servlet is deployed to the container we can access it from an url in a form of http://localhost:8080/app-name/helloworld.

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central