Search in sources :

Example 31 with ServletWebRequest

use of org.springframework.web.context.request.ServletWebRequest in project spring-framework by spring-projects.

the class DispatcherServlet method doDispatch.

/**
 * Process the actual dispatching to the handler.
 * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
 * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
 * to find the first that supports the handler class.
 * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
 * themselves to decide which methods are acceptable.
 * @param request current HTTP request
 * @param response current HTTP response
 * @throws Exception in case of any kind of processing failure
 */
@SuppressWarnings("deprecation")
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    try {
        ModelAndView mv = null;
        Exception dispatchException = null;
        try {
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);
            // Determine handler for the current request.
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null) {
                noHandlerFound(processedRequest, response);
                return;
            }
            // Determine handler adapter for the current request.
            HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
            // Process last-modified header, if supported by the handler.
            String method = request.getMethod();
            boolean isGet = HttpMethod.GET.matches(method);
            if (isGet || HttpMethod.HEAD.matches(method)) {
                long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
                if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }
            // Actually invoke the handler.
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }
            applyDefaultViewName(processedRequest, mv);
            mappedHandler.applyPostHandle(processedRequest, response, mv);
        } catch (Exception ex) {
            dispatchException = ex;
        } catch (Throwable err) {
            // As of 4.3, we're processing Errors thrown from handler methods as well,
            // making them available for @ExceptionHandler methods and other scenarios.
            dispatchException = new NestedServletException("Handler dispatch failed", err);
        }
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    } catch (Exception ex) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    } catch (Throwable err) {
        triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", err));
    } finally {
        if (asyncManager.isConcurrentHandlingStarted()) {
            // Instead of postHandle and afterCompletion
            if (mappedHandler != null) {
                mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
            }
        } else {
            // Clean up any resources used by a multipart request.
            if (multipartRequestParsed) {
                cleanupMultipart(processedRequest);
            }
        }
    }
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) NestedServletException(org.springframework.web.util.NestedServletException) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) 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 32 with ServletWebRequest

use of org.springframework.web.context.request.ServletWebRequest in project spring-framework by spring-projects.

the class ModelAndViewMethodReturnValueHandlerTests method setup.

@BeforeEach
public void setup() throws Exception {
    this.handler = new ModelAndViewMethodReturnValueHandler();
    this.mavContainer = new ModelAndViewContainer();
    this.webRequest = new ServletWebRequest(new MockHttpServletRequest());
    this.returnParamModelAndView = getReturnValueParam("modelAndView");
}
Also used : ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 33 with ServletWebRequest

use of org.springframework.web.context.request.ServletWebRequest in project spring-framework by spring-projects.

the class HttpEntityMethodProcessorTests method handleReturnValueWithETagAndETagFilter.

// SPR-13423
@Test
public void handleReturnValueWithETagAndETagFilter() throws Exception {
    String eTagValue = "\"deadb33f8badf00d\"";
    String content = "body";
    Method method = getClass().getDeclaredMethod("handle");
    MethodParameter returnType = new MethodParameter(method, -1);
    FilterChain chain = (req, res) -> {
        ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(eTagValue).body(content);
        try {
            ServletWebRequest requestToUse = new ServletWebRequest((HttpServletRequest) req, (HttpServletResponse) res);
            new HttpEntityMethodProcessor(Collections.singletonList(new StringHttpMessageConverter())).handleReturnValue(returnValue, returnType, mavContainer, requestToUse);
            assertThat(this.servletResponse.getContentAsString()).as("Response body was cached? It should be written directly to the raw response").isEqualTo(content);
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
    };
    this.servletRequest.setMethod("GET");
    new ShallowEtagHeaderFilter().doFilter(this.servletRequest, this.servletResponse, chain);
    assertThat(this.servletResponse.getStatus()).isEqualTo(200);
    assertThat(this.servletResponse.getHeader(HttpHeaders.ETAG)).isEqualTo(eTagValue);
    assertThat(this.servletResponse.getContentAsString()).isEqualTo(content);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) WebDataBinderFactory(org.springframework.web.bind.support.WebDataBinderFactory) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayList(java.util.ArrayList) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) MethodParameter(org.springframework.core.MethodParameter) Nullable(org.springframework.lang.Nullable) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) Method(java.lang.reflect.Method) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) ByteArrayHttpMessageConverter(org.springframework.http.converter.ByteArrayHttpMessageConverter) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) FilterChain(jakarta.servlet.FilterChain) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Serializable(java.io.Serializable) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) WebDataBinder(org.springframework.web.bind.WebDataBinder) ResponseEntity(org.springframework.http.ResponseEntity) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) ShallowEtagHeaderFilter(org.springframework.web.filter.ShallowEtagHeaderFilter) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ResponseEntity(org.springframework.http.ResponseEntity) MethodParameter(org.springframework.core.MethodParameter) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Example 34 with ServletWebRequest

use of org.springframework.web.context.request.ServletWebRequest in project spring-framework by spring-projects.

the class HttpEntityMethodProcessorMockTests method setup.

@BeforeEach
@SuppressWarnings("unchecked")
public void setup() throws Exception {
    stringHttpMessageConverter = mock(HttpMessageConverter.class);
    given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(TEXT_PLAIN));
    resourceMessageConverter = mock(HttpMessageConverter.class);
    given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
    given(resourceMessageConverter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.ALL));
    resourceRegionMessageConverter = mock(HttpMessageConverter.class);
    given(resourceRegionMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
    given(resourceRegionMessageConverter.getSupportedMediaTypes(any())).willReturn(Collections.singletonList(MediaType.ALL));
    processor = new HttpEntityMethodProcessor(Arrays.asList(stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter));
    Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class, Integer.TYPE, RequestEntity.class);
    paramHttpEntity = new MethodParameter(handle1, 0);
    paramRequestEntity = new MethodParameter(handle1, 3);
    paramResponseEntity = new MethodParameter(handle1, 1);
    paramInt = new MethodParameter(handle1, 2);
    returnTypeResponseEntity = new MethodParameter(handle1, -1);
    returnTypeResponseEntityProduces = new MethodParameter(getClass().getMethod("handle4"), -1);
    returnTypeHttpEntity = new MethodParameter(getClass().getMethod("handle2", HttpEntity.class), -1);
    returnTypeHttpEntitySubclass = new MethodParameter(getClass().getMethod("handle2x", HttpEntity.class), -1);
    returnTypeInt = new MethodParameter(getClass().getMethod("handle3"), -1);
    returnTypeResponseEntityResource = new MethodParameter(getClass().getMethod("handle5"), -1);
    mavContainer = new ModelAndViewContainer();
    servletRequest = new MockHttpServletRequest("GET", "/foo");
    servletResponse = new MockHttpServletResponse();
    webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
Also used : ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) Method(java.lang.reflect.Method) HttpMethod(org.springframework.http.HttpMethod) MethodParameter(org.springframework.core.MethodParameter) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 35 with ServletWebRequest

use of org.springframework.web.context.request.ServletWebRequest in project spring-framework by spring-projects.

the class ModelAndViewResolverMethodReturnValueHandlerTests method setup.

@BeforeEach
public void setup() {
    mavResolvers = new ArrayList<>();
    handler = new ModelAndViewResolverMethodReturnValueHandler(mavResolvers);
    mavContainer = new ModelAndViewContainer();
    request = new ServletWebRequest(new MockHttpServletRequest());
}
Also used : ModelAndViewContainer(org.springframework.web.method.support.ModelAndViewContainer) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)224 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)80 Test (org.junit.jupiter.api.Test)79 MethodParameter (org.springframework.core.MethodParameter)50 BeforeEach (org.junit.jupiter.api.BeforeEach)41 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)32 ModelAndViewContainer (org.springframework.web.method.support.ModelAndViewContainer)30 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)28 Method (java.lang.reflect.Method)21 Test (org.junit.Test)21 MockMultipartHttpServletRequest (org.springframework.web.testfixture.servlet.MockMultipartHttpServletRequest)21 MockMultipartFile (org.springframework.web.testfixture.servlet.MockMultipartFile)18 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)14 TestBean (org.springframework.beans.testfixture.beans.TestBean)14 RequestParam (org.springframework.web.bind.annotation.RequestParam)14 MockPart (org.springframework.web.testfixture.servlet.MockPart)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 MultipartFile (org.springframework.web.multipart.MultipartFile)13 SynthesizingMethodParameter (org.springframework.core.annotation.SynthesizingMethodParameter)11 IOException (java.io.IOException)10