Search in sources :

Example 46 with ServletException

use of jakarta.servlet.ServletException in project spring-framework by spring-projects.

the class HttpRequestHandlerTests method testHttpRequestHandlerServletPassThrough.

@Test
public void testHttpRequestHandlerServletPassThrough() throws Exception {
    MockServletContext servletContext = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.getBeanFactory().registerSingleton("myHandler", (HttpRequestHandler) (req, res) -> {
        assertThat(req).isSameAs(request);
        assertThat(res).isSameAs(response);
        String exception = request.getParameter("exception");
        if ("ServletException".equals(exception)) {
            throw new ServletException("test");
        }
        if ("IOException".equals(exception)) {
            throw new IOException("test");
        }
        res.getWriter().write("myResponse");
    });
    wac.setServletContext(servletContext);
    wac.refresh();
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    Servlet servlet = new HttpRequestHandlerServlet();
    servlet.init(new MockServletConfig(servletContext, "myHandler"));
    servlet.service(request, response);
    assertThat(response.getContentAsString()).isEqualTo("myResponse");
    request.setParameter("exception", "ServletException");
    assertThatExceptionOfType(ServletException.class).isThrownBy(() -> servlet.service(request, response)).withMessage("test");
    request.setParameter("exception", "IOException");
    assertThatIOException().isThrownBy(() -> servlet.service(request, response)).withMessage("test");
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) WebApplicationContext(org.springframework.web.context.WebApplicationContext) MockServletConfig(org.springframework.web.testfixture.servlet.MockServletConfig) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) Assertions.assertThatIOException(org.assertj.core.api.Assertions.assertThatIOException) Test(org.junit.jupiter.api.Test) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Servlet(jakarta.servlet.Servlet) HttpRequestHandler(org.springframework.web.HttpRequestHandler) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) ServletException(jakarta.servlet.ServletException) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Servlet(jakarta.servlet.Servlet) MockServletConfig(org.springframework.web.testfixture.servlet.MockServletConfig) IOException(java.io.IOException) Assertions.assertThatIOException(org.assertj.core.api.Assertions.assertThatIOException) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 47 with ServletException

use of jakarta.servlet.ServletException in project spring-framework by spring-projects.

the class SpringServletContainerInitializer method onStartup.

/**
 * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
 * implementations present on the application classpath.
 * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
 * Servlet containers will automatically scan the classpath for implementations of
 * Spring's {@code WebApplicationInitializer} interface and provide the set of all
 * such types to the {@code webAppInitializerClasses} parameter of this method.
 * <p>If no {@code WebApplicationInitializer} implementations are found on the classpath,
 * this method is effectively a no-op. An INFO-level log message will be issued notifying
 * the user that the {@code ServletContainerInitializer} has indeed been invoked but that
 * no {@code WebApplicationInitializer} implementations were found.
 * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
 * they will be instantiated (and <em>sorted</em> if the @{@link
 * org.springframework.core.annotation.Order @Order} annotation is present or
 * the {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
 * method will be invoked on each instance, delegating the {@code ServletContext} such
 * that each instance may register and configure servlets such as Spring's
 * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
 * or any other Servlet API features such as filters.
 * @param webAppInitializerClasses all implementations of
 * {@link WebApplicationInitializer} found on the application classpath
 * @param servletContext the servlet context to be initialized
 * @see WebApplicationInitializer#onStartup(ServletContext)
 * @see AnnotationAwareOrderComparator
 */
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
    List<WebApplicationInitializer> initializers = Collections.emptyList();
    if (webAppInitializerClasses != null) {
        initializers = new ArrayList<>(webAppInitializerClasses.size());
        for (Class<?> waiClass : webAppInitializerClasses) {
            // no matter what @HandlesTypes says...
            if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                try {
                    initializers.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(waiClass).newInstance());
                } catch (Throwable ex) {
                    throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                }
            }
        }
    }
    if (initializers.isEmpty()) {
        servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        return;
    }
    servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
    AnnotationAwareOrderComparator.sort(initializers);
    for (WebApplicationInitializer initializer : initializers) {
        initializer.onStartup(servletContext);
    }
}
Also used : ServletException(jakarta.servlet.ServletException)

Example 48 with ServletException

use of jakarta.servlet.ServletException in project spring-framework by spring-projects.

the class ServletForwardingController method handleRequestInternal.

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ServletContext servletContext = getServletContext();
    Assert.state(servletContext != null, "No ServletContext");
    RequestDispatcher rd = servletContext.getNamedDispatcher(this.servletName);
    if (rd == null) {
        throw new ServletException("No servlet with name '" + this.servletName + "' defined in web.xml");
    }
    // If already included, include again, else forward.
    if (useInclude(request, response)) {
        rd.include(request, response);
        if (logger.isTraceEnabled()) {
            logger.trace("Included servlet [" + this.servletName + "] in ServletForwardingController '" + this.beanName + "'");
        }
    } else {
        rd.forward(request, response);
        if (logger.isTraceEnabled()) {
            logger.trace("Forwarded to servlet [" + this.servletName + "] in ServletForwardingController '" + this.beanName + "'");
        }
    }
    return null;
}
Also used : ServletException(jakarta.servlet.ServletException) ServletContext(jakarta.servlet.ServletContext) RequestDispatcher(jakarta.servlet.RequestDispatcher)

Example 49 with ServletException

use of jakarta.servlet.ServletException in project spring-framework by spring-projects.

the class DispatcherServletTests method notDetectAllHandlerAdapters.

@Test
public void notDetectAllHandlerAdapters() throws ServletException, IOException {
    DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
    complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
    complexDispatcherServlet.setNamespace("test");
    complexDispatcherServlet.setDetectAllHandlerAdapters(false);
    complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
    // only ServletHandlerAdapter with bean name "handlerAdapter" detected
    MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do");
    MockHttpServletResponse response = new MockHttpServletResponse();
    complexDispatcherServlet.service(request, response);
    assertThat(response.getContentAsString()).isEqualTo("body");
    // SimpleControllerHandlerAdapter not detected
    request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do");
    response = new MockHttpServletResponse();
    complexDispatcherServlet.service(request, response);
    assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed0.jsp");
    assertThat(request.getAttribute("exception").getClass().equals(ServletException.class)).as("Exception exposed").isTrue();
}
Also used : ServletException(jakarta.servlet.ServletException) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) MockServletConfig(org.springframework.web.testfixture.servlet.MockServletConfig) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 50 with ServletException

use of jakarta.servlet.ServletException in project spring-framework by spring-projects.

the class DispatcherServletTests method simpleMappingExceptionResolverWithAllHandlers2.

@Test
public void simpleMappingExceptionResolverWithAllHandlers2() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/loc.do");
    request.addPreferredLocale(Locale.CANADA);
    request.addUserRole("role1");
    request.addParameter("servlet", "yes");
    MockHttpServletResponse response = new MockHttpServletResponse();
    complexDispatcherServlet.service(request, response);
    assertThat(response.getStatus()).isEqualTo(500);
    assertThat(response.getForwardedUrl()).as("forwarded to failed").isEqualTo("failed1.jsp");
    assertThat(request.getAttribute("exception") instanceof ServletException).as("Exception exposed").isTrue();
}
Also used : ServletException(jakarta.servlet.ServletException) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

ServletException (jakarta.servlet.ServletException)115 IOException (java.io.IOException)72 Test (org.junit.jupiter.api.Test)26 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)17 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 ServletContext (jakarta.servlet.ServletContext)14 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 BeforeEach (org.junit.jupiter.api.BeforeEach)12 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 Arrays (java.util.Arrays)10 Enumeration (java.util.Enumeration)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpHeaders (org.springframework.http.HttpHeaders)9 HttpMethod (org.springframework.http.HttpMethod)9 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)9 ServletRequest (jakarta.servlet.ServletRequest)8