Search in sources :

Example 16 with ServletException

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

the class JaasApiIntegrationFilter method doFilter.

/**
 * <p>
 * Attempts to obtain and run as a JAAS <code>Subject</code> using
 * {@link #obtainSubject(ServletRequest)}.
 * </p>
 *
 * <p>
 * If the <code>Subject</code> is <code>null</code> and <tt>createEmptySubject</tt> is
 * <code>true</code>, an empty, writeable <code>Subject</code> is used. This allows
 * for the <code>Subject</code> to be populated at the time of login. If the
 * <code>Subject</code> is <code>null</code>, the <code>FilterChain</code> continues
 * with no additional processing. If the <code>Subject</code> is not <code>null</code>
 * , the <code>FilterChain</code> is ran with
 * {@link Subject#doAs(Subject, PrivilegedExceptionAction)} in conjunction with the
 * <code>Subject</code> obtained.
 * </p>
 */
@Override
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    Subject subject = obtainSubject(request);
    if (subject == null && this.createEmptySubject) {
        this.logger.debug("Subject returned was null and createEmptySubject is true; " + "creating new empty subject to run as.");
        subject = new Subject();
    }
    if (subject == null) {
        this.logger.debug("Subject is null continue running with no Subject.");
        chain.doFilter(request, response);
        return;
    }
    this.logger.debug(LogMessage.format("Running as Subject %s", subject));
    try {
        Subject.doAs(subject, (PrivilegedExceptionAction<Object>) () -> {
            chain.doFilter(request, response);
            return null;
        });
    } catch (PrivilegedActionException ex) {
        throw new ServletException(ex.getMessage(), ex);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) Subject(javax.security.auth.Subject)

Example 17 with ServletException

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

the class ExceptionTranslationFilterTests method thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown.

@Test
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
    ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
    filter.afterPropertiesSet();
    Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
    for (Exception exception : exceptions) {
        FilterChain fc = mock(FilterChain.class);
        willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
        assertThatExceptionOfType(Exception.class).isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc)).isSameAs(exception);
    }
}
Also used : ServletException(jakarta.servlet.ServletException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 18 with ServletException

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

the class DispatcherServlet method render.

/**
 * Render the given ModelAndView.
 * <p>This is the last stage in handling a request. It may involve resolving the view by name.
 * @param mv the ModelAndView to render
 * @param request current HTTP servlet request
 * @param response current HTTP servlet response
 * @throws ServletException if view is missing or cannot be resolved
 * @throws Exception if there's a problem rendering the view
 */
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Determine locale for request and apply it to the response.
    Locale locale = (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());
    response.setLocale(locale);
    View view;
    String viewName = mv.getViewName();
    if (viewName != null) {
        // We need to resolve the view name.
        view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
        if (view == null) {
            throw new ServletException("Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" + getServletName() + "'");
        }
    } else {
        // No need to lookup: the ModelAndView object contains the actual View object.
        view = mv.getView();
        if (view == null) {
            throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " + "View object in servlet with name '" + getServletName() + "'");
        }
    }
    // Delegate to the View object for rendering.
    if (logger.isTraceEnabled()) {
        logger.trace("Rendering view [" + view + "] ");
    }
    try {
        if (mv.getStatus() != null) {
            request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, mv.getStatus());
            response.setStatus(mv.getStatus().value());
        }
        view.render(mv.getModelInternal(), request, response);
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error rendering view [" + view + "]", ex);
        }
        throw ex;
    }
}
Also used : Locale(java.util.Locale) ServletException(jakarta.servlet.ServletException) NestedServletException(org.springframework.web.util.NestedServletException) MultipartException(org.springframework.web.multipart.MultipartException) ServletException(jakarta.servlet.ServletException) BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) NestedServletException(org.springframework.web.util.NestedServletException) IOException(java.io.IOException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Example 19 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 20 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)127 IOException (java.io.IOException)78 Test (org.junit.jupiter.api.Test)31 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)23 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)23 ServletContext (jakarta.servlet.ServletContext)19 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 Enumeration (java.util.Enumeration)12 BeforeEach (org.junit.jupiter.api.BeforeEach)12 HttpHeaders (org.springframework.http.HttpHeaders)11 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 ServletRequest (jakarta.servlet.ServletRequest)10 ServletResponse (jakarta.servlet.ServletResponse)10 Arrays (java.util.Arrays)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpMethod (org.springframework.http.HttpMethod)9