How do I obtain ServletContext of another application?

The ServletContext.getContext(String uripath) enable us to access servlet context of another web application deployed on the same application server. A configuration need to be added to enable this feature.

In the example below we will forward the request from the current application to the /otherapp/hello.jsp page. We place a string in the request object attribute of the current application and going to show it in the hello.jsp page.

package org.kodejava.servlet;

import javax.servlet.RequestDispatcher;
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(urlPatterns = {"/context"})
public class GetAnotherContextServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get ServletContext of another application on the same Servlet
        // container. This allows us to forward request to another application
        // on the same application server.
        ServletContext ctx = request.getServletContext().getContext("/otherapp");

        // Set a request attribute and forward to hello.jsp page on another 
        // context.
        request.setAttribute("MESSAGE", "Hello There!");
        RequestDispatcher dispatcher = ctx.getRequestDispatcher("/hello.jsp");
        dispatcher.forward(request, response);
    }
}

To enable this feature in Tomcat we need to enable the crossContext attribute by setting the value to true, the default value is false. Update the server.xml file to add the following configuration inside the <Host> node.

<Context path="/webapp" debug="0" reloadable="true" crossContext="true"/>

Maven dependencies

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

Maven Central

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 a spring’s bean from a servlet?

I have created a servlet based web application, and I want to used Spring beans in it. So how do I do this in my servlet. Well, it is simple enough to do this. First, I have to obtain the Spring’s WebApplicationContext, from where I can grab the required bean by my servlet.

Let’s see some lines of code on how to do it, here we go:

package org.kodejava.servlet;

import org.kodejava.servlet.dao.UserDao;
import org.kodejava.servlet.model.User;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
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("/springbean")
public class SpringBeanServletExample extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        ServletContext context = getServletContext();
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        if (ctx != null) {
            UserDao dao = ctx.getBean("userDao", UserDao.class);

            Long userId = Long.valueOf(req.getParameter("user_id"));
            User user = dao.getUser(userId);

            res.setContentType("text/html");
            PrintWriter pw = res.getWriter();
            pw.print("User Details: " + user.toString());
            pw.flush();
        }
    }
}

Inside the Java Servlet doGet() method above I get the ServletContext, next the WebApplicationContextUtils help me to get Spring’s WebApplicationContext. With this object in my hand I can get my UserDao implementation and do a query from database.

Spring Bean Servlet Example

Spring Bean Servlet Example

Here are the supporting classes and the configurations.

UserDao.java

package org.kodejava.servlet.dao;

import org.kodejava.servlet.model.User;

public interface UserDao {
    User getUser(Long userId);
}

UserDaoImpl.java

package org.kodejava.servlet.dao.impl;

import org.kodejava.servlet.dao.UserDao;
import org.kodejava.servlet.model.User;

public class UserDaoImpl implements UserDao {
    @Override
    public User getUser(Long userId) {
        if (userId == 1L) {
            return new User(1L, "jdoe", "John Doe");
        }
        return new User();
    }
}

User.java

package org.kodejava.servlet.model;

import java.util.Objects;

public class User {
    private Long id;
    private String username;
    private String realName;

    public User() {
    }

    public User(Long id, String username, String realName) {
        this.id = id;
        this.username = username;
        this.realName = realName;
    }

    // Getters and Setters
}

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="org.kodejava.servlet.dao.impl.UserDaoImpl"/>

</beans>

web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

Maven dependencies

<!-- https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=org/springframework/spring-webmvc/5.3.22/spring-webmvc-5.3.22.jar -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.22</version>
</dependency>

Maven Central Maven Central