@SuppressWarnings("unchecked") protected Map<String, List<Resource>> getMappingLocations(HandlerMapping mapping) throws IllegalAccessException { Map<String, List<Resource>> mappingLocations = new LinkedHashMap<String, List<Resource>>(); if (mapping instanceof SimpleUrlHandlerMapping) { Field locationsField = ReflectionUtils .findField(ResourceHttpRequestHandler.class, "locations"); locationsField.setAccessible(true); for (Map.Entry<String, Object> entry : ((SimpleUrlHandlerMapping) mapping) .getHandlerMap().entrySet()) { ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) entry .getValue(); mappingLocations.put(entry.getKey(), (List<Resource>) locationsField.get(handler)); } } return mappingLocations; }
private void userUltraViresHandle ( HandlerMethod handlerMethod , HttpServletRequest request ) { /** * 大概流程 * {@link org.springframework.web.servlet.DispatcherServlet#doDispatch(HttpServletRequest , HttpServletResponse)} * {@link org.springframework.web.servlet.DispatcherServlet#getHandler(HttpServletRequest)} * {@link org.springframework.web.servlet.handler.AbstractHandlerMapping#getHandler(HttpServletRequest)} * {@link org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#getHandlerInternal(HttpServletRequest)} * ... ... * 在下面方法中Spring会把解析后的Path URI存放到域中 * {@link org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch(Object , String , HttpServletRequest)} * */ // /roles/{userId}/{roleId} final String uriVariables = ( String ) request.getAttribute( HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE ); // {userId=1, roleId=10000} final Map< String, String > decodedUriVariables = ( Map< String, String > ) request.getAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE ); }
@RequestMapping(value = "/pages/**", method = RequestMethod.GET) @ResponseBody public ResponseEntity<FileSystemResource> picture(HttpServletRequest request) { String resource = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring(1); Path path = fileService.getPageFile(resource).toPath(); File file = path.toAbsolutePath().toFile(); if (file.exists() && file.isFile()) { try { String detect = tika.detect(file); MediaType mediaType = MediaType.parseMediaType(detect); return ResponseEntity.ok().contentLength(file.length()).contentType(mediaType) .body(new FileSystemResource(file)); } catch (IOException e) { e.printStackTrace(); } } else { throw new ResourceNotFoundException(); } return null; }
/** * Get JSON representation of a workflow from generic git details * @param branch The branch of the repository * @return The JSON representation of the workflow */ @GetMapping(value="/workflows/**/*.git/{branch}/**", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Workflow getWorkflowJsonGeneric(@PathVariable("branch") String branch, HttpServletRequest request) { // The wildcard end of the URL is the path String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); // Construct a GitDetails object to search for in the database GitDetails gitDetails = WorkflowController.getGitDetails(11, path, branch); // Get workflow Workflow workflowModel = workflowService.getWorkflow(gitDetails); if (workflowModel == null) { throw new WorkflowNotFoundException(); } else { return workflowModel; } }
/** * Returns the media types that can be produced: * <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<?> returnValueClass, Type returnValueType) { Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); if (!CollectionUtils.isEmpty(mediaTypes)) { return new ArrayList<MediaType>(mediaTypes); } else if (!this.allSupportedMediaTypes.isEmpty()) { List<MediaType> result = new ArrayList<MediaType>(); for (HttpMessageConverter<?> converter : this.messageConverters) { if (converter instanceof GenericHttpMessageConverter && returnValueType != null) { if (((GenericHttpMessageConverter<?>) converter).canWrite(returnValueType, returnValueClass, null)) { result.addAll(converter.getSupportedMediaTypes()); } } else if (converter.canWrite(returnValueClass, null)) { result.addAll(converter.getSupportedMediaTypes()); } } return result; } else { return Collections.singletonList(MediaType.ALL); } }
/** * Return a Map with all URI template variables or an empty map. */ @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { @SuppressWarnings("unchecked") Map<String, String> uriTemplateVars = (Map<String, String>) webRequest.getAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); if (!CollectionUtils.isEmpty(uriTemplateVars)) { return new LinkedHashMap<String, String>(uriTemplateVars); } else { return Collections.emptyMap(); } }
/** * 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); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); handlerMapping.setInterceptors(new HandlerInterceptor[] { new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())}); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; }
@Test public void uriTemplateReuseCurrentRequestVars() throws Exception { Map<String, Object> model = new HashMap<String, Object>(); model.put("key1", "value1"); model.put("name", "value2"); model.put("key3", "value3"); Map<String, String> currentRequestUriTemplateVars = new HashMap<String, String>(); currentRequestUriTemplateVars.put("var1", "v1"); currentRequestUriTemplateVars.put("name", "v2"); currentRequestUriTemplateVars.put("var3", "v3"); this.request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, currentRequestUriTemplateVars); String url = "http://url.somewhere.com"; RedirectView redirectView = new RedirectView(url + "/{key1}/{var1}/{name}"); redirectView.renderMergedOutputModel(model, this.request, this.response); assertEquals(url + "/value1/v1/value2?key3=value3", this.response.getRedirectedUrl()); }
@RequestMapping(value = "/static/**", method = RequestMethod.GET) public void getFile(HttpServletResponse response, HttpServletRequest request) { try { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); PathMatchingResourcePatternResolver res = new PathMatchingResourcePatternResolver(); Resource template = res.getResource(path); if (!template.exists()) { log.info("file n/a... " + path); return; } org.apache.commons.io.IOUtils.copy(template.getInputStream(), response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error writing file to output stream", ex); } }
/** * Download a generated graph for a workflow in PNG format * @param domain The domain of the hosting site, Github or Gitlab * @param owner The owner of the repository * @param repoName The name of the repository * @param branch The branch of repository */ @GetMapping(value={"/graph/png/{domain}.com/{owner}/{repoName}/tree/{branch}/**", "/graph/png/{domain}.com/{owner}/{repoName}/blob/{branch}/**"}, produces="image/png") @ResponseBody public FileSystemResource downloadGraphPng(@PathVariable("domain") String domain, @PathVariable("owner") String owner, @PathVariable("repoName") String repoName, @PathVariable("branch") String branch, HttpServletRequest request, HttpServletResponse response) throws IOException { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); path = extractPath(path, 8); GitDetails gitDetails = getGitDetails(domain, owner, repoName, branch, path); response.setHeader("Content-Disposition", "inline; filename=\"graph.png\""); return workflowService.getWorkflowGraph("png", gitDetails); }
@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); }
@Override public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { if (this.mappings == null) { this.mappings = extractMappings(); } for (HandlerMapping mapping : this.mappings) { HandlerExecutionChain handler = mapping.getHandler(request); if (handler != null) { return handler; } } return null; }
@Before public void setUp() throws Exception { this.resolver = new MatrixVariableMapMethodArgumentResolver(); Method method = getClass().getMethod("handle", String.class, Map.class, MultiValueMap.class, MultiValueMap.class, Map.class); this.paramString = new SynthesizingMethodParameter(method, 0); this.paramMap = new SynthesizingMethodParameter(method, 1); this.paramMultivalueMap = new SynthesizingMethodParameter(method, 2); this.paramMapForPathVar = new SynthesizingMethodParameter(method, 3); this.paramMapWithName = new SynthesizingMethodParameter(method, 4); 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); }
@Test public void uriTemplateVariables() { PatternsRequestCondition patterns = new PatternsRequestCondition("/{path1}/{path2}"); RequestMappingInfo key = new RequestMappingInfo(patterns, null, null, null, null, null, null); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/1/2"); String lookupPath = new UrlPathHelper().getLookupPathForRequest(request); this.handlerMapping.handleMatch(key, lookupPath, request); @SuppressWarnings("unchecked") Map<String, String> uriVariables = (Map<String, String>) request.getAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); assertNotNull(uriVariables); assertEquals("1", uriVariables.get("path1")); assertEquals("2", uriVariables.get("path2")); }
/** * Get the JSON representation of a workflow from Github or Gitlab details * @param domain The domain of the hosting site, Github or Gitlab * @param owner The owner of the Github repository * @param repoName The name of the repository * @param branch The branch of repository * @return The JSON representation of the workflow */ @GetMapping(value = {"/workflows/{domain}.com/{owner}/{repoName}/tree/{branch}/**", "/workflows/{domain}.com/{owner}/{repoName}/blob/{branch}/**"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Workflow getWorkflowJson(@PathVariable("domain") String domain, @PathVariable("owner") String owner, @PathVariable("repoName") String repoName, @PathVariable("branch") String branch, HttpServletRequest request) { // The wildcard end of the URL is the path String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); path = WorkflowController.extractPath(path, 7); // Construct a GitDetails object to search for in the database GitDetails gitDetails = WorkflowController.getGitDetails(domain, owner, repoName, branch, path); // Get workflow Workflow workflowModel = workflowService.getWorkflow(gitDetails); if (workflowModel == null) { throw new WorkflowNotFoundException(); } else { return workflowModel; } }
@AllowCrossOrigin(from = "*") @AngularServiceOmitted @RequestMapping("/{id}/{team}/preview/**") public ResponseEntity previewTeamForGame(HttpServletResponse response, HttpServletRequest request, @PathVariable("id") int gameID, @PathVariable("team") String team) throws IOException { try { String mapping = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); String slug = mapping.split("preview/")[1]; InputStream inputStream = fileStorage.getFileDownloader(fileStorage.SITE_STORAGE_PATH + "/" + gameID + "/" + team + "/" + slug).body; IOUtils.copy(inputStream, response.getOutputStream()); return null; } catch (Exception e) { return new ResponseEntity("File not uploaded yet", HttpStatus.NOT_FOUND); } }
/** * Download a generated graph for a workflow in XDOT format * @param domain The domain of the hosting site, Github or Gitlab * @param owner The owner of the repository * @param repoName The name of the repository * @param branch The branch of repository */ @GetMapping(value={"/graph/xdot/{domain}.com/{owner}/{repoName}/tree/{branch}/**", "/graph/xdot/{domain}.com/{owner}/{repoName}/blob/{branch}/**"}, produces="text/vnd.graphviz") @ResponseBody public FileSystemResource downloadGraphDot(@PathVariable("domain") String domain, @PathVariable("owner") String owner, @PathVariable("repoName") String repoName, @PathVariable("branch") String branch, HttpServletRequest request, HttpServletResponse response) throws IOException { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); path = extractPath(path, 8); GitDetails gitDetails = getGitDetails(domain, owner, repoName, branch, path); response.setHeader("Content-Disposition", "inline; filename=\"graph.dot\""); return workflowService.getWorkflowGraph("xdot", gitDetails); }
/** * Display a page for a particular workflow from Github or Github format URL * @param domain The domain of the hosting site, Github or Gitlab * @param owner The owner of the repository * @param repoName The name of the repository * @param branch The branch of repository * @return The workflow view with the workflow as a model */ @GetMapping(value={"/workflows/{domain}.com/{owner}/{repoName}/tree/{branch}/**", "/workflows/{domain}.com/{owner}/{repoName}/blob/{branch}/**"}) public ModelAndView getWorkflow(@PathVariable("domain") String domain, @PathVariable("owner") String owner, @PathVariable("repoName") String repoName, @PathVariable("branch") String branch, HttpServletRequest request, RedirectAttributes redirectAttrs) { // The wildcard end of the URL is the path String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); path = extractPath(path, 7); // Construct a GitDetails object to search for in the database GitDetails gitDetails = getGitDetails(domain, owner, repoName, branch, path); // Get workflow return getWorkflow(gitDetails, redirectAttrs); }
@GetMapping("talk/**") @ResponseBody public ResponseEntity<String> talk(HttpServletRequest request) throws UrlNotFoundException { String fullUrl = (String) request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); logger.debug("Talking URL: {}", fullUrl); String url = getAppContextUrl(fullUrl); if (StringUtils.isEmpty(url)) { throw new UrlNotFoundException(fullUrl); } return new ResponseEntity<>(phraseService.getResponse(url), HttpStatus.OK); }
@Bean public HandlerMapping logoutFlowHandlerMapping() { final FlowHandlerMapping handler = new FlowHandlerMapping(); handler.setOrder(LOGOUT_FLOW_HANDLER_ORDER); handler.setFlowRegistry(logoutFlowRegistry()); final Object[] interceptors = new Object[]{localeChangeInterceptor()}; handler.setInterceptors(interceptors); return handler; }
@Bean public HandlerMapping loginFlowHandlerMapping() { final FlowHandlerMapping handler = new FlowHandlerMapping(); handler.setOrder(LOGOUT_FLOW_HANDLER_ORDER - 1); handler.setFlowRegistry(loginFlowRegistry()); handler.setInterceptors(loginFlowHandlerMappingInterceptors()); return handler; }
/** * 已登录 * * @param email * @param request * @param response */ private void onLoggedIn(String email, HttpServletRequest request, HttpServletResponse response) { User user = ApplicationContextHelper.getBean(UserService.class).getUser(email); // 设置到线程变量中 UserContext.setCurrentUser(user); AppService appService = ApplicationContextHelper.getBean(AppService.class); List<App> userAppList = appService.getUserAppList(UserContext.email()); Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); App currentApp = null; if (pathVariables.containsKey("appId")) { int appId = Integer.valueOf((String) pathVariables.get("appId")); currentApp = appService.getApp(appId); } else { currentApp = appService.getDefaultApp(user.getEmail()); } // 设置到request attribute中 request.setAttribute("name", user.getName()); request.setAttribute("email", user.getEmail()); request.setAttribute("isAdmin", user.getAdmin()); request.setAttribute("userAppList", userAppList); request.setAttribute("currentApp", currentApp); }
@Override @SuppressWarnings("unchecked") public void preHandle(WebRequest request) throws Exception { if (request.getUserPrincipal() == null) return; Map<String, String> o = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, WebRequest.SCOPE_REQUEST); if (o == null) return; if (o.get(USERNAME_ATTRIBUTE) != null && o.get(USERNAME_ATTRIBUTE).equals(LOGGED_IN_USER_PARAMETER)) { o.put(USERNAME_ATTRIBUTE, request.getUserPrincipal().getName()); } }
@Bean public HandlerMapping logoutFlowHandlerMapping() { FlowHandlerMapping handler = new FlowHandlerMapping(); handler.setOrder(3); handler.setFlowRegistry(this.logoutFlowRegistry()); Object[] interceptors = new Object[]{this.localeChangeInterceptor()}; handler.setInterceptors(interceptors); return handler; }
@Bean public HandlerMapping loginFlowHandlerMapping() { FlowHandlerMapping handler = new FlowHandlerMapping(); handler.setOrder(2); handler.setFlowRegistry(this.loginFlowRegistry()); handler.setInterceptors(this.loginFlowHandlerMappingInterceptors()); return handler; }
@ModelAttribute public void setCurrentNodePath() { Map<String, String> attributes = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); String root = attributes.get(PATH_VAR_ROOT); String child = attributes.get(PATH_VAR_CHILD); String path = PathUtil.build(root, child); currentNodePath.set(path); }
@RequestMapping(value = {"/pages/*.md"}, method = RequestMethod.GET) public String markdown(HttpServletRequest request, ModelMap map, Principal principal) { addCommonItems(map, principal); String resource = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring(1); Path path = fileService.getPageFile(resource).toPath(); map.addAttribute("text", parse(path)); return "page"; }
@SuppressWarnings("unchecked") private List<MediaType> getProducibleMediaTypes(HttpServletRequest request) { Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); if (!CollectionUtils.isEmpty(mediaTypes)) { return new ArrayList<MediaType>(mediaTypes); } else { return Collections.singletonList(MediaType.ALL); } }
protected Resource getResource(HttpServletRequest request) throws IOException { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (path == null) { throw new IllegalStateException("Required request attribute '" + HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set"); } path = processPath(path); if (!StringUtils.hasText(path) || isInvalidPath(path)) { if (logger.isTraceEnabled()) { logger.trace("Ignoring invalid resource path [" + path + "]"); } return null; } if (path.contains("%")) { try { // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars if (isInvalidPath(URLDecoder.decode(path, "UTF-8"))) { if (logger.isTraceEnabled()) { logger.trace("Ignoring invalid resource path with escape sequences [" + path + "]."); } return null; } } catch (IllegalArgumentException ex) { // ignore } } ResourceResolverChain resolveChain = new DefaultResourceResolverChain(getResourceResolvers()); Resource resource = resolveChain.resolveResource(request, path, getLocations()); if (resource == null || getResourceTransformers().isEmpty()) { return resource; } ResourceTransformerChain transformChain = new DefaultResourceTransformerChain(resolveChain, getResourceTransformers()); resource = transformChain.transform(request, resource); return resource; }
@SuppressWarnings("unchecked") private void extractHandlerMethodUriTemplates(String mappedPattern, String lookupPath, HttpServletRequest request) { Map<String, String> variables = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); int patternVariableCount = StringUtils.countOccurrencesOf(mappedPattern, "{"); if ((variables == null || patternVariableCount != variables.size()) && pathMatcher.match(mappedPattern, lookupPath)) { variables = pathMatcher.extractUriTemplateVariables(mappedPattern, lookupPath); Map<String, String> decodedVariables = urlPathHelper.decodePathVariables(request, variables); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedVariables); } }
@Override @SuppressWarnings({"unchecked"}) protected String resolvePathVariable(String pathVarName, Class<?> paramType, NativeWebRequest webRequest) throws Exception { HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); Map<String, String> uriTemplateVariables = (Map<String, String>) servletRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); if (uriTemplateVariables == null || !uriTemplateVariables.containsKey(pathVarName)) { throw new IllegalStateException( "Could not find @PathVariable [" + pathVarName + "] in @RequestMapping"); } return uriTemplateVariables.get(pathVarName); }
/** * Download a generated graph for a workflow in XDOT format * @param branch The branch of repository */ @GetMapping(value="/graph/xdot/**/*.git/{branch}/**", produces="text/vnd.graphviz") @ResponseBody public FileSystemResource downloadGraphDotGeneric(@PathVariable("branch") String branch, HttpServletRequest request, HttpServletResponse response) throws IOException { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); GitDetails gitDetails = getGitDetails(12, path, branch); response.setHeader("Content-Disposition", "inline; filename=\"graph.dot\""); return workflowService.getWorkflowGraph("xdot", gitDetails); }
@Override @SuppressWarnings("unchecked") protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception { Map<String, String> uriTemplateVars = (Map<String, String>) request.getAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); return (uriTemplateVars != null) ? uriTemplateVars.get(name) : null; }
/** * Expose URI template variables, matrix variables, and producible media types in the request. * @see HandlerMapping#URI_TEMPLATE_VARIABLES_ATTRIBUTE * @see HandlerMapping#MATRIX_VARIABLES_ATTRIBUTE * @see HandlerMapping#PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE */ @Override protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServletRequest request) { super.handleMatch(info, lookupPath, request); String bestPattern; Map<String, String> uriVariables; Map<String, String> decodedUriVariables; Set<String> patterns = info.getPatternsCondition().getPatterns(); if (patterns.isEmpty()) { bestPattern = lookupPath; uriVariables = Collections.emptyMap(); decodedUriVariables = Collections.emptyMap(); } else { bestPattern = patterns.iterator().next(); uriVariables = getPathMatcher().extractUriTemplateVariables(bestPattern, lookupPath); decodedUriVariables = getUrlPathHelper().decodePathVariables(request, uriVariables); } request.setAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedUriVariables); if (isMatrixVariableContentAvailable()) { Map<String, MultiValueMap<String, String>> matrixVars = extractMatrixVariables(request, uriVariables); request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, matrixVars); } if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) { Set<MediaType> mediaTypes = info.getProducesCondition().getProducibleMediaTypes(); request.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes); } }
private void beforeBodyWrite(Object body, ServletServerHttpRequest request) { Object pattern = request.getServletRequest() .getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (pattern != null && body instanceof ResourceSupport) { beforeBodyWrite(pattern.toString(), (ResourceSupport) body); } }
/** * Return a handler mapping ordered at 1 to map URL paths directly to * view names. To configure view controllers, override * {@link #addViewControllers}. */ @Bean public HandlerMapping viewControllerHandlerMapping() { ViewControllerRegistry registry = new ViewControllerRegistry(); registry.setApplicationContext(this.applicationContext); addViewControllers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); handlerMapping = (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping()); handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); handlerMapping.setInterceptors(getInterceptors()); handlerMapping.setCorsConfigurations(getCorsConfigurations()); return handlerMapping; }
/** * The method handlerMapping is responsbile for creating and configuring the locale change interceptor * @return A new request mapping handler mapping */ @Bean public HandlerMapping handlerMapping() { final LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("language"); final RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping(); requestMappingHandlerMapping.setInterceptors(new Object[] { localeChangeInterceptor }); return requestMappingHandlerMapping; }
@Test public void getResourceNoCache() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.setCacheSeconds(0); this.handler.handleRequest(this.request, this.response); assertEquals("no-store", this.response.getHeader("Cache-Control")); assertTrue(this.response.containsHeader("Last-Modified")); assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.css")); }
@Test public void getResourceWithHtmlMediaType() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); this.handler.handleRequest(this.request, this.response); assertEquals("text/html", this.response.getContentType()); assertEquals("max-age=3600", this.response.getHeader("Cache-Control")); assertTrue(this.response.containsHeader("Last-Modified")); assertEquals(this.response.getHeader("Last-Modified"), resourceLastModifiedDate("test/foo.html")); }