org.springframework.web.context.request.ServletWebRequest Java Examples

The following examples show how to use org.springframework.web.context.request.ServletWebRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnotationMethodHandlerAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception {
	if (responseEntity == null) {
		return;
	}
	HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
	HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
	if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
		((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
	}
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}
	Object body = responseEntity.getBody();
	if (body != null) {
		writeWithMessageConverters(body, inputMessage, outputMessage);
	}
	else {
		// flush headers
		outputMessage.getBody();
	}
}
 
Example #2
Source File: WebRequestDataBinderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testFieldPrefixCausesFieldResetWithIgnoreUnknownFields() throws Exception {
	TestBean target = new TestBean();
	WebRequestDataBinder binder = new WebRequestDataBinder(target);
	binder.setIgnoreUnknownFields(false);

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("_postProcessed", "visible");
	request.addParameter("postProcessed", "on");
	binder.bind(new ServletWebRequest(request));
	assertTrue(target.isPostProcessed());

	request.removeParameter("postProcessed");
	binder.bind(new ServletWebRequest(request));
	assertFalse(target.isPostProcessed());
}
 
Example #3
Source File: WebRequestDataBinderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testWithCommaSeparatedStringArray() throws Exception {
	TestBean target = new TestBean();
	WebRequestDataBinder binder = new WebRequestDataBinder(target);

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addParameter("stringArray", "bar");
	request.addParameter("stringArray", "abc");
	request.addParameter("stringArray", "123,def");
	binder.bind(new ServletWebRequest(request));
	assertEquals("Expected all three items to be bound", 3, target.getStringArray().length);

	request.removeParameter("stringArray");
	request.addParameter("stringArray", "123,def");
	binder.bind(new ServletWebRequest(request));
	assertEquals("Expected only 1 item to be bound", 1, target.getStringArray().length);
}
 
Example #4
Source File: ExpressionValueMethodArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setUp() throws Exception {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();
	resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory());

	Method method = getClass().getMethod("params", int.class, String.class, String.class);
	paramSystemProperty = new MethodParameter(method, 0);
	paramContextPath = new MethodParameter(method, 1);
	paramNotSupported = new MethodParameter(method, 2);

	webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(webRequest);
}
 
Example #5
Source File: ResponseEntityExceptionHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Customize the response for NoHandlerFoundException.
 * <p>This method delegates to {@link #handleExceptionInternal}.
 * @param ex the exception
 * @param headers the headers to be written to the response
 * @param status the selected response status
 * @param webRequest the current request
 * @return a {@code ResponseEntity} instance
 * @since 4.2.8
 */
@Nullable
protected ResponseEntity<Object> handleAsyncRequestTimeoutException(
		AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatus status, WebRequest webRequest) {

	if (webRequest instanceof ServletWebRequest) {
		ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
		HttpServletResponse response = servletWebRequest.getResponse();
		if (response != null && response.isCommitted()) {
			if (logger.isWarnEnabled()) {
				logger.warn("Async request timed out");
			}
			return null;
		}
	}

	return handleExceptionInternal(ex, null, headers, status, webRequest);
}
 
Example #6
Source File: ModelAttributeMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.request = new ServletWebRequest(new MockHttpServletRequest());
	this.container = new ModelAndViewContainer();
	this.processor = new ModelAttributeMethodProcessor(false);

	Method method = ModelAttributeHandler.class.getDeclaredMethod("modelAttribute",
			TestBean.class, Errors.class, int.class, TestBean.class,
			TestBean.class, TestBean.class);

	this.paramNamedValidModelAttr = new SynthesizingMethodParameter(method, 0);
	this.paramErrors = new SynthesizingMethodParameter(method, 1);
	this.paramInt = new SynthesizingMethodParameter(method, 2);
	this.paramModelAttr = new SynthesizingMethodParameter(method, 3);
	this.paramBindingDisabledAttr = new SynthesizingMethodParameter(method, 4);
	this.paramNonSimpleType = new SynthesizingMethodParameter(method, 5);

	method = getClass().getDeclaredMethod("annotatedReturnValue");
	this.returnParamNamedModelAttr = new MethodParameter(method, -1);

	method = getClass().getDeclaredMethod("notAnnotatedReturnValue");
	this.returnParamNonSimpleType = new MethodParameter(method, -1);
}
 
Example #7
Source File: RequestParamMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfMultipartFile() throws Exception {
	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	MultipartFile expected1 = new MockMultipartFile("mfilelist", "Hello World 1".getBytes());
	MultipartFile expected2 = new MockMultipartFile("mfilelist", "Hello World 2".getBytes());
	MultipartFile expected3 = new MockMultipartFile("other", "Hello World 3".getBytes());
	request.addFile(expected1);
	request.addFile(expected2);
	request.addFile(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, MultipartFile.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, MultipartFile> resultMap = (MultiValueMap<String, MultipartFile>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example #8
Source File: MatrixVariablesMethodArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	this.resolver = new MatrixVariableMethodArgumentResolver();

	Method method = getClass().getMethod("handle", String.class, List.class, int.class);
	this.paramString = new MethodParameter(method, 0);
	this.paramColors = new MethodParameter(method, 1);
	this.paramYear = new MethodParameter(method, 2);

	this.paramColors.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());

	this.mavContainer = new ModelAndViewContainer();
	this.request = new MockHttpServletRequest();
	this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse());

	Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<String, MultiValueMap<String, String>>();
	this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params);
}
 
Example #9
Source File: NotificationSubjectHandlerMethodArgumentResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void resolveArgument_notificationMessageTypeWithSubject_reportsErrors()
		throws Exception {
	// Arrange
	NotificationSubjectHandlerMethodArgumentResolver resolver = new NotificationSubjectHandlerMethodArgumentResolver();

	byte[] subscriptionRequestJsonContent = FileCopyUtils.copyToByteArray(
			new ClassPathResource("notificationMessage.json", getClass())
					.getInputStream());
	MockHttpServletRequest servletRequest = new MockHttpServletRequest();
	servletRequest.setContent(subscriptionRequestJsonContent);

	MethodParameter methodParameter = new MethodParameter(
			ReflectionUtils.findMethod(NotificationMethods.class,
					"subscriptionMethod", NotificationStatus.class),
			0);

	// Act
	Object argument = resolver.resolveArgument(methodParameter, null,
			new ServletWebRequest(servletRequest), null);

	// Assert
	assertThat(argument).isEqualTo("asdasd");
}
 
Example #10
Source File: RequestParamMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfilelist", "Hello World 1".getBytes());
	Part expected2 = new MockPart("mfilelist", "Hello World 2".getBytes());
	Part expected3 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, Part> resultMap = (MultiValueMap<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example #11
Source File: DefaultServerResponseBuilder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response,
		Context context) throws ServletException, IOException {

	try {
		writeStatusAndHeaders(response);

		long lastModified = headers().getLastModified();
		ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
		HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
		if (SAFE_METHODS.contains(httpMethod) &&
				servletWebRequest.checkNotModified(headers().getETag(), lastModified)) {
			return null;
		}
		else {
			return writeToInternal(request, response, context);
		}
	}
	catch (Throwable throwable) {
		return handleError(throwable, request, response, context);
	}
}
 
Example #12
Source File: RequestParamMapMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfilelist", "Hello World 1".getBytes());
	Part expected2 = new MockPart("mfilelist", "Hello World 2".getBytes());
	Part expected3 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	request.addPart(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, Part> resultMap = (MultiValueMap<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example #13
Source File: AnnotationMethodHandlerAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception {
	if (responseEntity == null) {
		return;
	}
	HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
	HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
	if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
		((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
	}
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}
	Object body = responseEntity.getBody();
	if (body != null) {
		writeWithMessageConverters(body, inputMessage, outputMessage);
	}
	else {
		// flush headers
		outputMessage.getBody();
	}
}
 
Example #14
Source File: ValidateCodeGranterFilter.java    From spring-security-oauth2-demo with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (requestMatcher.matches(request)){
        String grantType = getGrantType(request);
        if ("sms".equalsIgnoreCase(grantType) || "email".equalsIgnoreCase(grantType)){
            try {
                log.info("请求需要验证!验证请求:" + request.getRequestURI() + " 验证类型:" + grantType);
                validateCodeProcessorHolder.findValidateCodeProcessor(grantType)
                        .validate(new ServletWebRequest(request, response));
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }
    }
    filterChain.doFilter(request, response);
}
 
Example #15
Source File: RequestParamMapMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMapOfPart() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setContentType("multipart/form-data");
	Part expected1 = new MockPart("mfile", "Hello World".getBytes());
	Part expected2 = new MockPart("other", "Hello World 3".getBytes());
	request.addPart(expected1);
	request.addPart(expected2);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(Map.class, String.class, Part.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof Map);
	Map<String, Part> resultMap = (Map<String, Part>) result;
	assertEquals(2, resultMap.size());
	assertEquals(expected1, resultMap.get("mfile"));
	assertEquals(expected2, resultMap.get("other"));
}
 
Example #16
Source File: SmsCodeFilter.java    From FEBS-Security with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

    boolean match = false;
    for (String u : url) {
        if (pathMatcher.match(u, httpServletRequest.getRequestURI())) {
            match = true;
        }
    }
    if (match) {
        try {
            validateSmsCode(new ServletWebRequest(httpServletRequest));
        } catch (ValidateCodeException e) {
            authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            return;
        }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example #17
Source File: RequestParamMapMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapOfMultipartFile() throws Exception {
	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	MultipartFile expected1 = new MockMultipartFile("mfilelist", "Hello World 1".getBytes());
	MultipartFile expected2 = new MockMultipartFile("mfilelist", "Hello World 2".getBytes());
	MultipartFile expected3 = new MockMultipartFile("other", "Hello World 3".getBytes());
	request.addFile(expected1);
	request.addFile(expected2);
	request.addFile(expected3);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annot(requestParam().noName()).arg(MultiValueMap.class, String.class, MultipartFile.class);
	Object result = resolver.resolveArgument(param, null, webRequest, null);

	assertTrue(result instanceof MultiValueMap);
	MultiValueMap<String, MultipartFile> resultMap = (MultiValueMap<String, MultipartFile>) result;
	assertEquals(2, resultMap.size());
	assertEquals(2, resultMap.get("mfilelist").size());
	assertEquals(expected1, resultMap.get("mfilelist").get(0));
	assertEquals(expected2, resultMap.get("mfilelist").get(1));
	assertEquals(1, resultMap.get("other").size());
	assertEquals(expected3, resultMap.get("other").get(0));
}
 
Example #18
Source File: SmsCodeFilter.java    From SpringAll with MIT License 6 votes vote down vote up
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
    String smsCodeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsCode");
    String mobileInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "smsCode");

    SmsCode codeInSession = (SmsCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_SMS_CODE + mobileInRequest);

    if (StringUtils.isBlank(smsCodeInRequest)) {
        throw new ValidateCodeException("验证码不能为空!");
    }
    if (codeInSession == null) {
        throw new ValidateCodeException("验证码不存在!");
    }
    if (codeInSession.isExpire()) {
        sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
        throw new ValidateCodeException("验证码已过期!");
    }
    if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), smsCodeInRequest)) {
        throw new ValidateCodeException("验证码不正确!");
    }
    sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);

}
 
Example #19
Source File: ValidateCodeFilter.java    From SpringAll with MIT License 6 votes vote down vote up
private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
    ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
    String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");

    if (StringUtils.isBlank(codeInRequest)) {
        throw new ValidateCodeException("验证码不能为空!");
    }
    if (codeInSession == null) {
        throw new ValidateCodeException("验证码不存在!");
    }
    if (codeInSession.isExpire()) {
        sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);
        throw new ValidateCodeException("验证码已过期!");
    }
    if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) {
        throw new ValidateCodeException("验证码不正确!");
    }
    sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE);

}
 
Example #20
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	container = new ModelAndViewContainer();
	servletRequest = new MockHttpServletRequest();
	servletRequest.setMethod("POST");
	servletResponse = new MockHttpServletResponse();
	request = new ServletWebRequest(servletRequest, servletResponse);
	this.factory = new ValidatingBinderFactory();

	Method method = getClass().getDeclaredMethod("handle",
			List.class, SimpleBean.class, MultiValueMap.class, String.class);
	paramGenericList = new MethodParameter(method, 0);
	paramSimpleBean = new MethodParameter(method, 1);
	paramMultiValueMap = new MethodParameter(method, 2);
	paramString = new MethodParameter(method, 3);
	returnTypeString = new MethodParameter(method, -1);
}
 
Example #21
Source File: ExpressionValueMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setUp() throws Exception {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	context.refresh();
	resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory());

	Method method = getClass().getMethod("params", int.class, String.class, String.class);
	paramSystemProperty = new MethodParameter(method, 0);
	paramContextPath = new MethodParameter(method, 1);
	paramNotSupported = new MethodParameter(method, 2);

	webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());

	// Expose request to the current thread (for SpEL expressions)
	RequestContextHolder.setRequestAttributes(webRequest);
}
 
Example #22
Source File: SmsCodeFilter.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    if (StringUtils.equalsIgnoreCase("/login/mobile", httpServletRequest.getRequestURI())
            && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
        try {
            validateCode(new ServletWebRequest(httpServletRequest));
        } catch (Exception e) {
            authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new AuthenticationServiceException(e.getMessage()));
            return;
        }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
}
 
Example #23
Source File: ServletWebArgumentResolverAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected NativeWebRequest getWebRequest() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes instanceof ServletRequestAttributes) {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
		return new ServletWebRequest(servletRequestAttributes.getRequest());
	}
	return null;
}
 
Example #24
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveOptionalPartListNotPresent() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	webRequest = new ServletWebRequest(request);

	Object actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null);
	assertEquals("Invalid argument value", Optional.empty(), actualValue);

	actualValue = resolver.resolveArgument(optionalPartList, null, webRequest, null);
	assertEquals("Invalid argument value", Optional.empty(), actualValue);
}
 
Example #25
Source File: MatrixVariablesMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	this.resolver = new MatrixVariableMethodArgumentResolver();
	this.mavContainer = new ModelAndViewContainer();
	this.request = new MockHttpServletRequest();
	this.webRequest = new ServletWebRequest(request, new MockHttpServletResponse());

	Map<String, MultiValueMap<String, String>> params = new LinkedHashMap<>();
	this.request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, params);
}
 
Example #26
Source File: AnnotationMethodHandlerAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {

	ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);
	Method handlerMethod = methodResolver.resolveHandlerMethod(request);
	ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);
	ServletWebRequest webRequest = new ServletWebRequest(request, response);
	ExtendedModelMap implicitModel = new BindingAwareModelMap();

	Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);
	ModelAndView mav =
			methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);
	methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);
	return mav;
}
 
Example #27
Source File: AbstractRequestAttributesArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	HttpServletRequest request = new MockHttpServletRequest();
	HttpServletResponse response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(request, response);

	this.resolver = createResolver();

	this.handleMethod = AbstractRequestAttributesArgumentResolverTests.class
			.getDeclaredMethod(getHandleMethodName(), Foo.class, Foo.class, Foo.class, Optional.class);
}
 
Example #28
Source File: ValidateController.java    From SpringAll with MIT License 5 votes vote down vote up
@GetMapping("/code/sms")
public void createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) {
    SmsCode smsCode = createSMSCode();
    sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_SMS_CODE + mobile, smsCode);
    // 输出验证码到控制台代替短信发送服务
    System.out.println("您的登录验证码为:" + smsCode.getCode() + ",有效时间为60秒");
}
 
Example #29
Source File: RequestPartMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveOptionalPartArgumentNotPresent() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("POST");
	request.setContentType("multipart/form-data");
	webRequest = new ServletWebRequest(request);

	Object actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null);
	assertEquals("Invalid argument value", Optional.empty(), actualValue);

	actualValue = resolver.resolveArgument(optionalPart, null, webRequest, null);
	assertEquals("Invalid argument value", Optional.empty(), actualValue);
}
 
Example #30
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {

	List<HttpMessageConverter<?>> converters = Arrays.asList(
			new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter());

	this.handler = new ResponseBodyEmitterReturnValueHandler(converters);
	this.request = new MockHttpServletRequest();
	this.response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, this.response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}