How do I read text file in Servlet?

This example show you how to read a text file in a servlet. Using the ServletContext.getResourceAsStream() method will enable you to read a file whether the web application is deployed in an exploded format or in a war file archive.

The following servlet read the configuration.properties file from the /WEB-INF directory in our web application. The configuration.properties file is just a regular text file with the following contents.

app.appname=Servlet Examples
app.version=1.0
app.copyright=2021

Here is our ReadTextFileServlet servlet class.

package org.kodejava.servlet;

import javax.servlet.ServletContext;
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.*;

@WebServlet(name = "ReadTextFileServlet", urlPatterns = "/read-text-file")
public class ReadTextFileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");

        // We are going to read a file called configuration.properties. This
        // file is placed under the WEB-INF directory.
        String filename = "/WEB-INF/configuration.properties";

        ServletContext context = getServletContext();

        // First get the file InputStream using ServletContext.getResourceAsStream()
        // method.
        InputStream is = context.getResourceAsStream(filename);
        if (is != null) {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            PrintWriter writer = response.getWriter();
            String text;

            // We read the file line by line and later will be displayed on the
            // browser page.
            while ((text = reader.readLine()) != null) {
                writer.println(text + "</br>");
            }
        }
    }
}

To access the servlet you can type http://localhost:8080/read-text-file in your browser URL address bar.

Maven dependencies

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

Maven Central

How do I share object or data between users in web application?

In a web application there are different type of scope where we can store object or data. There are a page, request, session and application scope.

To share data between users of the web application we can put a shared object in application scope which can be done by calling setAttribute() method of the ServletContext. By this way data can then be accessing by other users by calling the getAttribute() method of the ServletContext.

Let’s see the example code in a simple servlet.

package org.kodejava.servlet;

import javax.servlet.ServletContext;
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;

@WebServlet(name = "SharedObjectServlet", urlPatterns = "/shared-object")
public class ApplicationContextScopeAttribute extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = this.getServletContext();
        context.setAttribute("HELLO.WORLD", "Hello World 123");
    }
}

And here is what we code in the JSP page to access it.

<%= request.getServletContext().getAttribute("HELLO.WORLD") %>

Maven dependencies

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

Maven Central

How do I get my web application real path?

This code helps you to get the physical path where your web application is deployed on the server. It may be useful, so you can for instance read or write files on the server. Please be aware that this method will only work when your web application is deployed in an exploded way, if it was deployed in a war format the getRealPath() method just return null.

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;

@WebServlet(name = "RealPathServlet", urlPatterns = "/real-path")
public class GetWebApplicationPathServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = getServletContext().getRealPath("/");
        PrintWriter writer = response.getWriter();
        writer.println("Application path: " + path);
    }
}

If you tried access the servlet you’ll get an output like:

Application path: F:\Wayan\Kodejava\kodejava-example\kodejava-servlet\target\kodejava-servlet\

Maven dependencies

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

Maven Central

How do I use JNDI to get database connection or data source?

package org.kodejava.jndi;

import javax.naming.Context;
import javax.naming.InitialContext;
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 javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "JNDITestServlet", urlPatterns = "/jndi-datasource-test")
public class JNDITestServlet extends HttpServlet implements Servlet {

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {

        // This implementation of doGet method show us an example to use
        // conn obtained in the getConnection() method.
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        try (Connection connection = getConnection()) {
            // A query to get current date time from Oracle database
            String sql = "select current_timestamp() as SYSDATE";
            PreparedStatement statement = connection.prepareStatement(sql);
            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                Date date = rs.getTimestamp("SYSDATE");
                writer.println("The current date is " + format.format(date));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Get a database connection from the registered data source in the
     * servlet container. To registered the JNDI data source you should
     * refer to your servlet container documentation.
     *
     * @return a database connection
     */
    private Connection getConnection() {
        Connection connection = null;
        try {
            InitialContext initialContext = new InitialContext();
            Context context = (Context) initialContext.lookup("java:/comp/env");
            DataSource dataSource = (DataSource) context.lookup("jdbc/DataSource");
            connection = dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
}

Configure the JNDI DataSource in Tomcat conf/context.xml configuration file. And don’t forget to copy the JDBC driver library to Tomcat’s lib directory.

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    ...
    <Resource name="jdbc/DataSource" auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="" driverClassName="com.mysql.cj.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/kodejava"/>
    ...
</Context>

Maven dependencies

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

Maven Central

How do I check if parameter is exists in servlet request?

ServletRequest or HttpServletRequest object has a map object that maps parameter name and its value. By accessing this map we can check if a parameter was passed in servlet request. Let’s see the example below.

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;

@WebServlet(name = "ParameterCheck", urlPatterns = "/parameter-check")
public class ParameterCheck extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        // Check if username parameter exists
        if (req.getParameterMap().containsKey("username")) {
            String username = req.getParameter("username");
            System.out.println("username = " + username);
        }

        // Check if password parameter exists
        if (req.getParameterMap().containsKey("password")) {
            String password = req.getParameter("password");
            System.out.println("password = " + password);
        }
    }
}

Maven dependencies

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

Maven Central