Skip to content

Commit af0998d

Browse files
Merge pull request #18818 from martin-blazevic/article/BAEL-9099
[BAEL-9099] Different Ways to Get Servlet Context
2 parents 50218a9 + 1956bed commit af0998d

File tree

4 files changed

+211
-0
lines changed

4 files changed

+211
-0
lines changed

web-modules/jakarta-servlets-2/pom.xml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,26 @@
5555
</exclusion>
5656
</exclusions>
5757
</dependency>
58+
59+
<dependency>
60+
<groupId>org.eclipse.jetty</groupId>
61+
<artifactId>jetty-server</artifactId>
62+
<version>${jetty.version}</version>
63+
<scope>test</scope>
64+
</dependency>
65+
<dependency>
66+
<groupId>org.eclipse.jetty</groupId>
67+
<artifactId>jetty-servlet</artifactId>
68+
<version>${jetty.version}</version>
69+
<scope>test</scope>
70+
</dependency>
71+
<dependency>
72+
<groupId>org.eclipse.jetty</groupId>
73+
<artifactId>jetty-client</artifactId>
74+
<version>${jetty.version}</version>
75+
<scope>test</scope>
76+
</dependency>
77+
5878
</dependencies>
5979

6080
<build>
@@ -79,6 +99,7 @@
7999
<jakarta.servlet-api.version>6.1.0</jakarta.servlet-api.version>
80100
<jakarta.servlet.jsp-api.version>4.0.0</jakarta.servlet.jsp-api.version>
81101
<jakarta.servlet.jsp.jstl-api.version>3.0.0</jakarta.servlet.jsp.jstl-api.version>
102+
<jetty.version>11.0.24</jetty.version>
82103
<gson.version>2.11.0</gson.version>
83104
<commons-fileupload2-jakarta-servlet6.version>2.0.0-M2</commons-fileupload2-jakarta-servlet6.version>
84105
</properties>
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.context;
2+
3+
import jakarta.servlet.ServletConfig;
4+
import jakarta.servlet.ServletContext;
5+
import jakarta.servlet.ServletException;
6+
import jakarta.servlet.annotation.WebServlet;
7+
import jakarta.servlet.http.HttpServlet;
8+
import jakarta.servlet.http.HttpServletRequest;
9+
import jakarta.servlet.http.HttpServletResponse;
10+
11+
import java.io.IOException;
12+
13+
@WebServlet(ContextServlet.PATH)
14+
public class ContextServlet extends HttpServlet {
15+
16+
protected static final String PATH = "/context";
17+
18+
protected static final String LABEL_FROM_HTTP_SERVLET = "1) From HttpServlet: ";
19+
protected static final String LABEL_FROM_SERVLET_CONFIG = "2) From ServletConfig: ";
20+
protected static final String LABEL_FROM_HTTP_SERVLET_REQUEST = "3) From HttpServletRequest: ";
21+
protected static final String LABEL_FROM_HTTP_SESSION = "4) From HttpSession: ";
22+
23+
@Override
24+
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
25+
26+
resp.setContentType("text/plain");
27+
28+
// 1. Direct Access From the Servlet
29+
ServletContext contextFromServlet = this.getServletContext();
30+
resp.getWriter()
31+
.println(LABEL_FROM_HTTP_SERVLET + contextFromServlet);
32+
33+
resp.getWriter()
34+
.println();
35+
36+
// 2. Accessing Through the ServletConfig
37+
ServletConfig config = this.getServletConfig();
38+
ServletContext contextFromConfig = config.getServletContext();
39+
resp.getWriter()
40+
.println(LABEL_FROM_SERVLET_CONFIG + contextFromConfig);
41+
42+
resp.getWriter()
43+
.println();
44+
45+
// 3. Getting the Context From the HttpServletRequest (Servlet 3.0+)
46+
ServletContext contextFromRequest = req.getServletContext();
47+
resp.getWriter()
48+
.println(LABEL_FROM_HTTP_SERVLET_REQUEST + contextFromRequest);
49+
50+
resp.getWriter()
51+
.println();
52+
53+
// 4. Retrieving Through the Session Object
54+
ServletContext contextFromSession = req.getSession()
55+
.getServletContext();
56+
resp.getWriter()
57+
.println(LABEL_FROM_HTTP_SESSION + contextFromSession);
58+
}
59+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.context;
2+
3+
import org.eclipse.jetty.client.HttpClient;
4+
import org.eclipse.jetty.server.Server;
5+
import org.eclipse.jetty.servlet.ServletContextHandler;
6+
import org.junit.jupiter.api.*;
7+
8+
import java.net.InetSocketAddress;
9+
10+
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
11+
public abstract class BaseServletTest {
12+
13+
protected HttpClient httpClient;
14+
protected Server server;
15+
16+
protected int port() {
17+
return 0; // (random) available port
18+
}
19+
20+
protected String host() {
21+
return "localhost";
22+
}
23+
24+
protected String contextPath() {
25+
return "/";
26+
}
27+
28+
@BeforeAll
29+
void startup() throws Exception {
30+
httpClient = new HttpClient();
31+
httpClient.start();
32+
33+
ServletContextHandler context = prepareContextHandler();
34+
35+
server = new Server(new InetSocketAddress(host(), port()));
36+
server.setHandler(context);
37+
server.start();
38+
}
39+
40+
private ServletContextHandler prepareContextHandler() {
41+
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
42+
context.setContextPath(contextPath());
43+
configure(context);
44+
return context;
45+
}
46+
47+
protected abstract void configure(ServletContextHandler context);
48+
49+
@AfterAll
50+
void shutdown() throws Exception {
51+
if (server != null) {
52+
server.stop();
53+
}
54+
if (httpClient != null) {
55+
httpClient.stop();
56+
}
57+
}
58+
59+
protected String baseUri() {
60+
String uri = server.getURI()
61+
.toString();
62+
return uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri;
63+
}
64+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.baeldung.context;
2+
3+
import org.apache.http.HttpStatus;
4+
import org.eclipse.jetty.client.api.ContentResponse;
5+
import org.eclipse.jetty.servlet.ServletContextHandler;
6+
import org.junit.jupiter.api.Test;
7+
8+
import java.net.URI;
9+
import java.util.List;
10+
import java.util.Set;
11+
import java.util.stream.Collectors;
12+
13+
import static org.junit.jupiter.api.Assertions.*;
14+
15+
class ContextServletUnitTest extends BaseServletTest {
16+
17+
private static final List<String> CONTEXT_LABELS = List.of(ContextServlet.LABEL_FROM_HTTP_SERVLET, ContextServlet.LABEL_FROM_SERVLET_CONFIG,
18+
ContextServlet.LABEL_FROM_HTTP_SERVLET_REQUEST, ContextServlet.LABEL_FROM_HTTP_SESSION);
19+
20+
@Override
21+
protected void configure(ServletContextHandler ctx) {
22+
ctx.addServlet(ContextServlet.class, ContextServlet.PATH);
23+
}
24+
25+
@Test
26+
void givenContextServlet_whenGetRequest_thenResponseContainsSameContextInstance() throws Exception {
27+
ContentResponse response = httpClient.GET(URI.create(baseUri() + ContextServlet.PATH));
28+
29+
assertEquals(HttpStatus.SC_OK, response.getStatus());
30+
31+
String body = response.getContentAsString();
32+
33+
assertContextLinesIn(body);
34+
35+
List<String> tokens = parseServletContextTokens(body);
36+
assertAllEqual(tokens);
37+
}
38+
39+
private static void assertContextLinesIn(String body) {
40+
for (String label : CONTEXT_LABELS) {
41+
assertTrue(body.contains(label));
42+
}
43+
}
44+
45+
private static List<String> parseServletContextTokens(String body) {
46+
List<String> targetLines = body.lines()
47+
.filter(line -> CONTEXT_LABELS.stream()
48+
.anyMatch(line::startsWith))
49+
.collect(Collectors.toList());
50+
51+
assertEquals(CONTEXT_LABELS.size(), targetLines.size());
52+
53+
return targetLines.stream()
54+
.map(line -> {
55+
int indexOf = line.indexOf(':');
56+
assertTrue(indexOf >= 0);
57+
return line.substring(indexOf + 1)
58+
.trim();
59+
})
60+
.collect(Collectors.toList());
61+
}
62+
63+
private static void assertAllEqual(List<String> tokens) {
64+
Set<String> distinct = Set.copyOf(tokens);
65+
assertEquals(1, distinct.size());
66+
}
67+
}

0 commit comments

Comments
 (0)