How To Read HTTP Request Header in Spring MVC

This short tutorial is about how to read the HTTP request header in the spring framework.

While refactoring a REST service, I came across code duplicates.

There were 5 similar methods, whereby only the RequestBody and the Return method differed minimally.

In this case, it’s a GET request which serializes an RDF record into different formats on request.

Now I wanted to convert these 5 methods into a single method.
With the @RequestHeader annotation, this is no problem.

 
 @RequestMapping(value = {"/rest/**"},
        method = RequestMethod.GET)
    public @ResponseBody ResponseEntity getContainer(@RequestHeader(value="Accept") String acceptHeader, HttpServletRequest request) {

        log.debug("Request to get container: {} in format: {}", path, acceptHeader);

        // dummy code to get path
        String path = "";

        // return rdf in requested format
        return new ResponseEntity<>(containerService.find(path).toString(acceptHeader), HttpStatus.OK);
    }

How to resolve slashes in path variable in Spring MVC

Today I stumbled across a problem where a slash can occur in a path variable.

The contents of the path variable can look like this:
1/53879d5c-b07b-44f2-9a77-b99f67bb8481 or even 1/2/53879d5c-b07b-44f2-9a77-b99f67bb8481

At the backend, I need the full path in a variable because the path can contain several slashes but does not have to.

Let’s have a look at this as a code example to make it clear.

@GetMapping("/rest/{path}")
public @ResponseBody ResponseEntity<Container> getContainerByPath(@PathVariable String path) {

  return containerService.getByPath(path);

}

The path /1/53879d5c-b07b-44f2-9a77-b99f67bb8481 will not work.

The solution is HttpServletRequest.

// /rest/1/53879d5c-b07b-44f2-9a77-b99f67bb8481
@GetMapping("/rest/**")
public @ResponseBody ResponseEntity<Container> getContainerByPath(HttpServletRequest request) {

  String path = extractPath(request);

  return containerService.getByPath(path);

}
private String extractPath(HttpServletRequest request) {

  String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
  String matchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); // /rest/**

  return new AntPathMatcher().extractPathWithinPattern(matchPattern, path); // 1/53879d5c-b07b-44f2-9a77-b99f67bb8481
}