Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions web-modules/jakarta-servlets-2/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,26 @@
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>${jetty.version}</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand All @@ -79,6 +99,7 @@
<jakarta.servlet-api.version>6.1.0</jakarta.servlet-api.version>
<jakarta.servlet.jsp-api.version>4.0.0</jakarta.servlet.jsp-api.version>
<jakarta.servlet.jsp.jstl-api.version>3.0.0</jakarta.servlet.jsp.jstl-api.version>
<jetty.version>11.0.24</jetty.version>
<gson.version>2.11.0</gson.version>
<commons-fileupload2-jakarta-servlet6.version>2.0.0-M2</commons-fileupload2-jakarta-servlet6.version>
</properties>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.baeldung.context;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(ContextServlet.PATH)
public class ContextServlet extends HttpServlet {

protected static final String PATH = "/context";

protected static final String LABEL_FROM_HTTP_SERVLET = "1) From HttpServlet: ";
protected static final String LABEL_FROM_SERVLET_CONFIG = "2) From ServletConfig: ";
protected static final String LABEL_FROM_HTTP_SERVLET_REQUEST = "3) From HttpServletRequest: ";
protected static final String LABEL_FROM_HTTP_SESSION = "4) From HttpSession: ";

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

resp.setContentType("text/plain");

// 1. Direct Access From the Servlet
ServletContext contextFromServlet = this.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SERVLET + contextFromServlet);

resp.getWriter()
.println();

// 2. Accessing Through the ServletConfig
ServletConfig config = this.getServletConfig();
ServletContext contextFromConfig = config.getServletContext();
resp.getWriter()
.println(LABEL_FROM_SERVLET_CONFIG + contextFromConfig);

resp.getWriter()
.println();

// 3. Getting the Context From the HttpServletRequest (Servlet 3.0+)
ServletContext contextFromRequest = req.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SERVLET_REQUEST + contextFromRequest);

resp.getWriter()
.println();

// 4. Retrieving Through the Session Object
ServletContext contextFromSession = req.getSession()
.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SESSION + contextFromSession);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.baeldung.context;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.jupiter.api.*;

import java.net.InetSocketAddress;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class BaseServletTest {

protected HttpClient httpClient;
protected Server server;

protected int port() {
return 0; // (random) available port
}

protected String host() {
return "localhost";
}

protected String contextPath() {
return "/";
}

@BeforeAll
void startup() throws Exception {
httpClient = new HttpClient();
httpClient.start();

ServletContextHandler context = prepareContextHandler();

server = new Server(new InetSocketAddress(host(), port()));
server.setHandler(context);
server.start();
}

private ServletContextHandler prepareContextHandler() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath(contextPath());
configure(context);
return context;
}

protected abstract void configure(ServletContextHandler context);

@AfterAll
void shutdown() throws Exception {
if (server != null) {
server.stop();
}
if (httpClient != null) {
httpClient.stop();
}
}

protected String baseUri() {
String uri = server.getURI()
.toString();
return uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.baeldung.context;

import org.apache.http.HttpStatus;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.jupiter.api.Test;

import java.net.URI;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.*;

class ContextServletUnitTest extends BaseServletTest {

private static final List<String> CONTEXT_LABELS = List.of(ContextServlet.LABEL_FROM_HTTP_SERVLET, ContextServlet.LABEL_FROM_SERVLET_CONFIG,
ContextServlet.LABEL_FROM_HTTP_SERVLET_REQUEST, ContextServlet.LABEL_FROM_HTTP_SESSION);

@Override
protected void configure(ServletContextHandler ctx) {
ctx.addServlet(ContextServlet.class, ContextServlet.PATH);
}

@Test
void givenContextServlet_whenGetRequest_thenResponseContainsSameContextInstance() throws Exception {
ContentResponse response = httpClient.GET(URI.create(baseUri() + ContextServlet.PATH));

assertEquals(HttpStatus.SC_OK, response.getStatus());

String body = response.getContentAsString();

assertContextLinesIn(body);

List<String> tokens = parseServletContextTokens(body);
assertAllEqual(tokens);
}

private static void assertContextLinesIn(String body) {
for (String label : CONTEXT_LABELS) {
assertTrue(body.contains(label));
}
}

private static List<String> parseServletContextTokens(String body) {
List<String> targetLines = body.lines()
.filter(line -> CONTEXT_LABELS.stream()
.anyMatch(line::startsWith))
.collect(Collectors.toList());

assertEquals(CONTEXT_LABELS.size(), targetLines.size());

return targetLines.stream()
.map(line -> {
int indexOf = line.indexOf(':');
assertTrue(indexOf >= 0);
return line.substring(indexOf + 1)
.trim();
})
.collect(Collectors.toList());
}

private static void assertAllEqual(List<String> tokens) {
Set<String> distinct = Set.copyOf(tokens);
assertEquals(1, distinct.size());
}
}