Java Code Examples for org.springframework.web.servlet.HandlerMapping

The following examples show how to use org.springframework.web.servlet.HandlerMapping. These examples are extracted from open source projects. 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
@Test
public void emptyHandlerMappings() {
	ApplicationContext context = initContext(WebConfig.class);

	Map<String, HandlerMapping> handlerMappings = context.getBeansOfType(HandlerMapping.class);
	assertFalse(handlerMappings.containsKey("viewControllerHandlerMapping"));
	assertFalse(handlerMappings.containsKey("resourceHandlerMapping"));
	assertFalse(handlerMappings.containsKey("defaultServletHandlerMapping"));

	Object nullBean = context.getBean("viewControllerHandlerMapping");
	assertTrue(nullBean.equals(null));

	nullBean = context.getBean("resourceHandlerMapping");
	assertTrue(nullBean.equals(null));

	nullBean = context.getBean("defaultServletHandlerMapping");
	assertTrue(nullBean.equals(null));
}
 
Example 2
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at 1 to map URL paths directly to
 * view names. To configure view controllers, override
 * {@link #addViewControllers}.
 */
@Bean
@Nullable
public HandlerMapping viewControllerHandlerMapping(PathMatcher mvcPathMatcher,
		UrlPathHelper mvcUrlPathHelper,
		FormattingConversionService mvcConversionService,
		ResourceUrlProvider mvcResourceUrlProvider) {
	ViewControllerRegistry registry = new ViewControllerRegistry(this.applicationContext);
	addViewControllers(registry);

	AbstractHandlerMapping handlerMapping = registry.buildHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher);
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper);
	handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example 3
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
@Nullable
public HandlerMapping resourceHandlerMapping(UrlPathHelper mvcUrlPathHelper,
		PathMatcher mvcPathMatcher,
		ContentNegotiationManager mvcContentNegotiationManager,
		FormattingConversionService mvcConversionService,
		ResourceUrlProvider mvcResourceUrlProvider) {
	Assert.state(this.applicationContext != null, "No ApplicationContext set");
	Assert.state(this.servletContext != null, "No ServletContext set");

	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
			this.servletContext, mvcContentNegotiationManager, mvcUrlPathHelper);
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher);
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper);
	handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example 4
@Test
public void uriTemplateVarAndRequestParam() throws Exception {
	request.addParameter("age", "35");

	Map<String, String> uriTemplateVars = new HashMap<String, String>();
	uriTemplateVars.put("name", "nameValue");
	uriTemplateVars.put("age", "25");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	TestBean target = new TestBean();
	WebDataBinder binder = new ExtendedServletRequestDataBinder(target, "");
	((ServletRequestDataBinder) binder).bind(request);

	assertEquals("nameValue", target.getName());
	assertEquals(35, target.getAge());
}
 
Example 5
Source Project: singleton   Source File: APISecurityInterceptor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get data and verify token
 *
 * @param request HttpServletRequest object
 * @return If true, authentication is passed, otherwise not
 */
@SuppressWarnings("unchecked")
private boolean verifyRightForResouceAccess(HttpServletRequest request) {
    String token = request.getHeader(ConstantsKeys.TOKEN);
    if (StringUtils.isEmpty(token))
        return false;
    String[] tArray = token.split(ConstantsKeys.VIP.hashCode() + "");
    Map<String, String> pathVariables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    String productName = pathVariables.get(ConstantsKeys.PRODUCTNAME) == null
            ? request.getParameter(ConstantsKeys.PRODUCTNAME) : pathVariables.get(ConstantsKeys.PRODUCTNAME);
    String version = pathVariables.get(ConstantsKeys.VERSION) == null
            ? request.getParameter(ConstantsKeys.VERSION) : pathVariables.get(ConstantsKeys.VERSION);
    if (!StringUtils.isEmpty(productName) && !StringUtils.isEmpty(version)) {
        String productName_version = tArray[0];
        if (!productName_version.equals((productName + ConstantsChar.UNDERLINE + version).hashCode()+""))
            return false;
    }
    if (token.indexOf(String.valueOf(ConstantsKeys.VIP.hashCode())) <= 0)
        return false;
    return true;
}
 
Example 6
@SuppressWarnings("unchecked")
private static void validateLocale(HttpServletRequest request, List<String> sourceLocales2)
		throws VIPAPIException {
	Map<String, String> pathVariables = (Map<String, String>) request
			.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
	String locale = pathVariables.get(APIParamName.LOCALE) == null ? request
			.getParameter(APIParamName.LOCALE) : pathVariables
			.get(APIParamName.LOCALE);
	if (StringUtils.isEmpty(locale)) {
		return;
	}
	if (!RegExpValidatorUtils.IsLetterAndNumberAndValidchar(locale)) {
		throw new VIPAPIException(ValidationMsg.LOCALE_NOT_VALIDE);
	}else if (!sourceLocales2.contains(locale)) {
		throw new VIPAPIException(ValidationMsg.LOCALE_NOT_VALIDE);
	}
}
 
Example 7
@Test
public void uriTemplateVarAndRequestParam() throws Exception {
	request.addParameter("age", "35");

	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "nameValue");
	uriTemplateVars.put("age", "25");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	TestBean target = new TestBean();
	WebDataBinder binder = new ExtendedServletRequestDataBinder(target, "");
	((ServletRequestDataBinder) binder).bind(request);

	assertEquals("nameValue", target.getName());
	assertEquals(35, target.getAge());
}
 
Example 8
Source Project: foremast   Source File: HandlerMappingIntrospector.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find the {@link HandlerMapping} that would handle the given request and
 * return it as a {@link MatchableHandlerMapping} that can be used to test
 * request-matching criteria.
 * <p>If the matching HandlerMapping is not an instance of
 * {@link MatchableHandlerMapping}, an IllegalStateException is raised.
 * @param request the current request
 * @return the resolved matcher, or {@code null}
 * @throws Exception if any of the HandlerMapping's raise an exception
 */
public HandlerExecutionChain getHandlerExecutionChain(HttpServletRequest request) throws Exception {
    Assert.notNull(this.handlerMappings, "Handler mappings not initialized");
    HttpServletRequest wrapper = new RequestAttributeChangeIgnoringWrapper(request);
    for (HandlerMapping handlerMapping : this.handlerMappings) {
        Object handler = handlerMapping.getHandler(wrapper);
        if (handler == null) {
            continue;
        }
        if (handler instanceof HandlerExecutionChain) {
            return (HandlerExecutionChain)handler;
        }
        throw new IllegalStateException("HandlerMapping is not a MatchableHandlerMapping");
    }
    return null;
}
 
Example 9
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
public HandlerMapping resourceHandlerMapping() {
	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
			this.servletContext, mvcContentNegotiationManager());
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping != null) {
		handlerMapping.setPathMatcher(mvcPathMatcher());
		handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
		handlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider()));
		handlerMapping.setCorsConfigurations(getCorsConfigurations());
	}
	else {
		handlerMapping = new EmptyHandlerMapping();
	}
	return handlerMapping;
}
 
Example 10
@Test
public void resolveArgumentWrappedAsOptional() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	@SuppressWarnings("unchecked")
	Optional<String> result = (Optional<String>)
			resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory);
	assertEquals("PathVariable not resolved correctly", "value", result.get());

	@SuppressWarnings("unchecked")
	Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES);
	assertNotNull(pathVars);
	assertEquals(1, pathVars.size());
	assertEquals(Optional.of("value"), pathVars.get("name"));
}
 
Example 11
@Test
public void resolveArgumentWithExistingPathVars() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	uriTemplateVars.put("oldName", "oldValue");
	request.setAttribute(View.PATH_VARIABLES, uriTemplateVars);

	String result = (String) resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null);
	assertEquals("PathVariable not resolved correctly", "value", result);

	@SuppressWarnings("unchecked")
	Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES);
	assertNotNull(pathVars);
	assertEquals(2, pathVars.size());
	assertEquals("value", pathVars.get("name"));
	assertEquals("oldValue", pathVars.get("oldName"));
}
 
Example 12
@Test  // SPR-14005
public void doOverwriteExistingCacheControlHeaders() throws Exception {
	this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css");
	this.response.setHeader("Cache-Control", "no-store");

	this.handler.handleRequest(this.request, this.response);

	assertEquals("max-age=3600", this.response.getHeader("Cache-Control"));
}
 
Example 13
Source Project: beihu-boot   Source File: FileApi.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("{bucketName}/**")
public ResponseEntity<Resource> downloadFile(@PathVariable("bucketName") String bucketName,
                                             HttpServletRequest request)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException,
        InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException,
        XmlPullParserException, ErrorResponseException {

    String path = String.valueOf(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
    String objectName = path.substring(path.indexOf(bucketName) + bucketName.length() + 1);

    InputStream objectStream = minioTemplate.getObject(bucketName, objectName);
    String fileName = objectName.substring(objectName.lastIndexOf('/') + 1);

    return ResponseEntity.ok()
            .contentType(MediaType.IMAGE_JPEG)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
            .body(new InputStreamResource(objectStream));
}
 
Example 14
Source Project: java-technology-stack   Source File: ReactiveTypeHandlerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void mediaTypes() throws Exception {

	// Media type from request
	this.servletRequest.addHeader("Accept", "text/event-stream");
	testSseResponse(true);

	// Media type from "produces" attribute
	Set<MediaType> types = Collections.singleton(MediaType.TEXT_EVENT_STREAM);
	this.servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, types);
	testSseResponse(true);

	// No media type preferences
	testSseResponse(false);
}
 
Example 15
Source Project: zfile   Source File: DirectLinkController.java    License: MIT License 5 votes vote down vote up
/**
 * 获取指定驱动器, 某个文件的直链, 然后重定向过去.
 * @param   driveId
 *          驱动器 ID
 *
 * @return  重定向至文件直链
 */
@GetMapping("/directlink/{driveId}/**")
public String directlink(@PathVariable("driveId") Integer driveId, final HttpServletRequest request) {
    String path = (String) request.getAttribute(
            HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    AntPathMatcher apm = new AntPathMatcher();
    String filePath = apm.extractPathWithinPattern(bestMatchPattern, path);

    if (filePath.length() > 0 && filePath.charAt(0) != ZFileConstant.PATH_SEPARATOR_CHAR) {
        filePath = "/" + filePath;
    }

    AbstractBaseFileService fileService = driveContext.get(driveId);
    FileItemDTO fileItem = fileService.getFileItem(filePath);

    String url = fileItem.getUrl();

    int queryIndex = url.indexOf('?');

    if (queryIndex != -1) {
        String origin = url.substring(0, queryIndex);
        String queryString = url.substring(queryIndex + 1);

        url = URLUtil.encode(origin) + "?" + URLUtil.encode(queryString);
    } else {
        url = URLUtil.encode(url);
    }


    if (Objects.equals(fileItem.getType(), FileTypeEnum.FOLDER)) {
        return "redirect:" + fileItem.getUrl();
    } else {
        return "redirect:" + url;
    }
}
 
Example 16
@Test
public void testRequestAttributeMatcher() throws Exception {

	String producibleMediaTypes = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;

	this.mockMvc.perform(get("/1"))
		.andExpect(request().attribute(producibleMediaTypes, hasItem(MediaType.APPLICATION_JSON)))
		.andExpect(request().attribute(producibleMediaTypes, not(hasItem(MediaType.APPLICATION_XML))));
}
 
Example 17
Source Project: foremast   Source File: HandlerMappingIntrospector.java    License: Apache License 2.0 5 votes vote down vote up
private static List<HandlerMapping> initHandlerMappings(ApplicationContext applicationContext) {
    Map<String, HandlerMapping> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
            applicationContext, HandlerMapping.class, true, false);
    if (!beans.isEmpty()) {
        List<HandlerMapping> mappings = new ArrayList<>(beans.values());
        AnnotationAwareOrderComparator.sort(mappings);
        return Collections.unmodifiableList(mappings);
    }
    return Collections.unmodifiableList(initFallback(applicationContext));
}
 
Example 18
private static List<HandlerMapping> initHandlerMappings(ApplicationContext applicationContext) {
	Map<String, HandlerMapping> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
			applicationContext, HandlerMapping.class, true, false);
	if (!beans.isEmpty()) {
		List<HandlerMapping> mappings = new ArrayList<HandlerMapping>(beans.values());
		AnnotationAwareOrderComparator.sort(mappings);
		return Collections.unmodifiableList(mappings);
	}
	return Collections.unmodifiableList(initFallback(applicationContext));
}
 
Example 19
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	@SuppressWarnings("unchecked")
	Map<String, MultiValueMap<String, String>> matrixVariables =
			(Map<String, MultiValueMap<String, String>>) request.getAttribute(
					HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

	if (CollectionUtils.isEmpty(matrixVariables)) {
		return Collections.emptyMap();
	}

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	MatrixVariable ann = parameter.getParameterAnnotation(MatrixVariable.class);
	Assert.state(ann != null, "No MatrixVariable annotation");
	String pathVariable = ann.pathVar();

	if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
		MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
		if (mapForPathVariable == null) {
			return Collections.emptyMap();
		}
		map.putAll(mapForPathVariable);
	}
	else {
		for (MultiValueMap<String, String> vars : matrixVariables.values()) {
			vars.forEach((name, values) -> {
				for (String value : values) {
					map.add(name, value);
				}
			});
		}
	}

	return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}
 
Example 20
/**
 * Extract a URL path from the given request,
 * suitable for view name extraction.
 * @param request current HTTP request
 * @return the URL to use for view name extraction
 */
protected String extractOperableUrl(HttpServletRequest request) {
	String urlPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
	if (!StringUtils.hasText(urlPath)) {
		urlPath = getUrlPathHelper().getLookupPathForRequest(request);
	}
	return urlPath;
}
 
Example 21
/**
 * Returns the media types that can be produced. The resulting media types are:
 * <ul>
 * <li>The producible media types specified in the request mappings, or
 * <li>Media types of configured converters that can write the specific return value, or
 * <li>{@link MediaType#ALL}
 * </ul>
 * @since 4.2
 */
@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(
		HttpServletRequest request, Class<?> valueClass, @Nullable Type targetType) {

	Set<MediaType> mediaTypes =
			(Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		return new ArrayList<>(mediaTypes);
	}
	else if (!this.allSupportedMediaTypes.isEmpty()) {
		List<MediaType> result = new ArrayList<>();
		for (HttpMessageConverter<?> converter : this.messageConverters) {
			if (converter instanceof GenericHttpMessageConverter && targetType != null) {
				if (((GenericHttpMessageConverter<?>) converter).canWrite(targetType, valueClass, null)) {
					result.addAll(converter.getSupportedMediaTypes());
				}
			}
			else if (converter.canWrite(valueClass, null)) {
				result.addAll(converter.getSupportedMediaTypes());
			}
		}
		return result;
	}
	else {
		return Collections.singletonList(MediaType.ALL);
	}
}
 
Example 22
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    Object attribute = request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (attribute instanceof LinkedHashSet) {
        @SuppressWarnings("unchecked") LinkedHashSet<MediaType> lhs = (LinkedHashSet<MediaType>) attribute;
        if (lhs.remove(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON)) {
            lhs.add(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON);
        }
    }
    return true;
}
 
Example 23
@Test
public void createBinder() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<String, String>();
	uriTemplateVars.put("name", "nameValue");
	uriTemplateVars.put("age", "25");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	TestBean target = new TestBean();
	WebDataBinder binder = new ExtendedServletRequestDataBinder(target, "");
	((ServletRequestDataBinder) binder).bind(request);

	assertEquals("nameValue", target.getName());
	assertEquals(25, target.getAge());
}
 
Example 24
@SuppressWarnings("unchecked")
private MultiValueMap<String, String> getMatrixVariables(String pathVarName) {
	Map<String, MultiValueMap<String, String>> matrixVariables =
			(Map<String, MultiValueMap<String, String>>) this.request.getAttribute(
					HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
	matrixVariables.put(pathVarName, params);

	return params;
}
 
Example 25
@Test
public void mapPathToLocation() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("GET");
	request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/testStylesheet.css");

	ResourceHttpRequestHandler handler = getHandler("/resources/**");
	handler.handleRequest(request, this.response);

	assertEquals("test stylesheet content", this.response.getContentAsString());
}
 
Example 26
@Before
public void setup() throws Exception {
	this.resolver = new MatrixVariableMapMethodArgumentResolver();
	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 27
@Test
public void partialContentMultipleByteRanges() throws Exception {
	this.request.addHeader("Range", "bytes=0-1, 4-5, 8-9");
	this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt");
	this.handler.handleRequest(this.request, this.response);

	assertEquals(206, this.response.getStatus());
	assertTrue(this.response.getContentType().startsWith("multipart/byteranges; boundary="));

	String boundary = "--" + this.response.getContentType().substring(31);

	String content = this.response.getContentAsString();
	String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true);

	assertEquals(boundary, ranges[0]);
	assertEquals("Content-Type: text/plain", ranges[1]);
	assertEquals("Content-Range: bytes 0-1/10", ranges[2]);
	assertEquals("So", ranges[3]);

	assertEquals(boundary, ranges[4]);
	assertEquals("Content-Type: text/plain", ranges[5]);
	assertEquals("Content-Range: bytes 4-5/10", ranges[6]);
	assertEquals(" t", ranges[7]);

	assertEquals(boundary, ranges[8]);
	assertEquals("Content-Type: text/plain", ranges[9]);
	assertEquals("Content-Range: bytes 8-9/10", ranges[10]);
	assertEquals("t.", ranges[11]);
}
 
Example 28
@Test
public void mapPathToLocation() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod("GET");
	request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/testStylesheet.css");

	ResourceHttpRequestHandler handler = getHandler("/resources/**");
	handler.handleRequest(request, this.response);

	assertEquals("test stylesheet content", this.response.getContentAsString());
}
 
Example 29
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE with a mapped
 * default servlet handler. To configure "default" Servlet handling,
 * override {@link #configureDefaultServletHandling}.
 */
@Bean
@Nullable
public HandlerMapping defaultServletHandlerMapping() {
	Assert.state(this.servletContext != null, "No ServletContext set");
	DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(this.servletContext);
	configureDefaultServletHandling(configurer);
	return configurer.buildHandlerMapping();
}
 
Example 30
@SuppressWarnings("unchecked")
protected final Map<String, String> getUriTemplateVariables(NativeWebRequest request) {
    Map<String, String> variables =
            (Map<String, String>) request.getAttribute(
                    HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    return (variables != null) ? variables : Collections.<String, String>emptyMap();
}