Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Different Ways to Get Servlet Context ([email protected]) #18079

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.baeldung.servlet.context;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class ContextListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
sce.getServletContext().setAttribute("contextPath", sce.getServletContext().getContextPath());
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
sce.getServletContext().log("ServletContextListener destroyed");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.baeldung.servlet.context;

import jakarta.servlet.ServletContext;
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(name = "get-servlet-context", value = "servlet-context")
public class GetServletContext extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletContext context = getServletContext();

// Next, we’ll fetch an initialization parameter from the context
String message = context.getInitParameter("message");

// Finally, we’ll send a response back to the user
response.getWriter().write(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.baeldung.servlet.context;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class ServletRequest extends HttpServlet{

@Override
protected void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException {
ServletContext context = servletRequest.getServletContext();

// Next, we’ll fetch an initialization parameter from the context
String message = context.getInitParameter("message");

// Finally, we’ll send a response back to the user
servletResponse.getWriter().append(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.baeldung.servlet.context;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.mockito.Mockito.*;

class ContextListenerTest {

/**
* Tests the contextInitialized method of ContextListener.
* <p>
* This test checks if the context attribute "contextPath" is correctly set to the context path
* obtained from the ServletContext during initialization.
*/
@Test
void whenContextInitialized_thenSetsContextPathAttribute() {
// Arrange
ServletContext mockServletContext = Mockito.mock(ServletContext.class);
ServletContextEvent mockServletContextEvent = Mockito.mock(ServletContextEvent.class);
when(mockServletContextEvent.getServletContext()).thenReturn(mockServletContext);
when(mockServletContext.getContextPath()).thenReturn("/exampleContext");

ContextListener contextListener = new ContextListener();

// Act
contextListener.contextInitialized(mockServletContextEvent);

// Assert
verify(mockServletContext).setAttribute("contextPath", "/exampleContext");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package com.baeldung.servlet.context;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.io.PrintWriter;

import static org.mockito.Mockito.*;

class GetServletContextTest {

/**
* Test that the `doGet` method writes the correct message
* retrieved from the ServletContext's init parameter `message`.
*/
@Test
void whenDoGet_thenWritesMessageFromServletContext() throws Exception {
// Arrange
GetServletContext servlet = new GetServletContext();
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
ServletContext mockServletContext = mock(ServletContext.class);
PrintWriter writer = mock(PrintWriter.class);

when(mockResponse.getWriter()).thenReturn(writer);
when(mockServletContext.getInitParameter("message")).thenReturn("Hello, World!");
servlet.init(mock(ServletConfig.class));
when(servlet.getServletContext()).thenReturn(mockServletContext);

// Act
servlet.doGet(mockRequest, mockResponse);

// Assert
verify(mockResponse.getWriter()).write("Hello, World!");
}

/**
* Test that the `doGet` method handles a null message gracefully
* when the ServletContext's init parameter `message` is not set.
*/
@Test
void whenDoGet_thenHandlesNullMessageGracefully() throws Exception {
// Arrange
GetServletContext servlet = new GetServletContext();
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
ServletContext mockServletContext = mock(ServletContext.class);
PrintWriter writer = mock(PrintWriter.class);

when(mockResponse.getWriter()).thenReturn(writer);
when(mockServletContext.getInitParameter("message")).thenReturn(null);
servlet.init(mock(ServletConfig.class));

when(servlet.getServletContext()).thenReturn(mockServletContext);

// Act
servlet.doGet(mockRequest, mockResponse);

// Assert
verify(mockResponse.getWriter()).write((String) null);
}

/**
* Test that the `doGet` method interacts with the ServletContext
* to retrieve the `message` init parameter.
*/
@Test
void whenDoGet_thenInteractsWithServletContext() throws Exception {
// Arrange
GetServletContext servlet = new GetServletContext();
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
ServletContext mockServletContext = mock(ServletContext.class);
PrintWriter writer = mock(PrintWriter.class);

when(mockResponse.getWriter()).thenReturn(writer);
when(mockServletContext.getInitParameter("message")).thenReturn("Test Message");
servlet.init(mock(ServletConfig.class));
when(servlet.getServletContext()).thenReturn(mockServletContext);

// Act
servlet.doGet(mockRequest, mockResponse);

// Assert
verify(mockServletContext).getInitParameter("message");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package com.baeldung.servlet.context;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mockit.Mocked;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockServletContext;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class ServletRequestTest {

@Mocked
HttpServletRequest request;
@Mocked
HttpServletResponse response;
private ServletRequest servletRequest;
private StringWriter stringWriter;

@BeforeEach
void setUp() {
servletRequest = new ServletRequest();
stringWriter = new StringWriter();
}

@Test
void givenHttpServletContext_thenReturnsServletContextParameters() throws IOException {
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);

String message = "Welcome to baeldung!";
MockServletContext mockContext = new MockServletContext();
mockContext.addInitParameter("message", message);

when(request.getServletContext()).thenReturn(mockContext);

when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));

servletRequest.doGet(request, response);

assertEquals(message, stringWriter.toString());
}

@Test
void givenHttpServletContext_whenMocked_thenReturnsServletContextParameters() throws IOException {
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
String message = "Welcome to baeldung!";
MockServletContext mockContext = new MockServletContext();
mockContext.addInitParameter("message", message);

when(request.getServletContext()).thenReturn(mockContext);

when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));
servletRequest.doGet(request, response);

assertEquals(message, stringWriter.toString());
}

@Test
void whenNoInitParameter_thenReturnsEmptyResponse() throws IOException {
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);

MockServletContext mockContext = new MockServletContext();
// No parameter is added here

when(request.getServletContext()).thenReturn(mockContext);
when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));

servletRequest.doGet(request, response);

assertEquals("null", stringWriter.toString());
}

@Test
void whenInitParameterIsNull_thenReturnsEmptyResponse() throws IOException {
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);

MockServletContext mockContext = new MockServletContext();
mockContext.addInitParameter("message", null); // Explicitly setting parameter to null

when(request.getServletContext()).thenReturn(mockContext);
when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));

servletRequest.doGet(request, response);

assertEquals("null", stringWriter.toString());
}
}