4

I'm constructing a new URL in a Spring MVC controller, to be passed back to the client. Currently I'm trying this:

// httpRequest is the current HttpServletRequest

new URL(httpRequest.getProtocol(),
    httpRequest.getServerName(),
    httpRequest.getServerPort(),
    httpRequest.getContextPath().concat("/foo/bar.html"));

Problem is that httpRequest.getProtocol() gives me "HTTP/1.1" instead of just "HTTP". I can trim it but wondered if there was a more elegant way.

user3120173
  • 1,758
  • 7
  • 25
  • 39
  • 1
    Possible duplicate of http://stackoverflow.com/questions/19598690/how-to-get-host-name-with-port-from-a-http-or-https-request & http://stackoverflow.com/questions/1104611/java-string-representation-of-just-the-host-scheme-possibly-port-from-servlet – OO7 Jun 18 '15 at 05:40

2 Answers2

15

The protocol is HTTP/1.1, since it is a specific version of HTTP. The scheme as given by ServletRequest#getSchemeitself is http:

new URL(httpRequest.getScheme(),
httpRequest.getServerName(),
httpRequest.getServerPort(),
httpRequest.getContextPath().concat("/foo/bar.html"));
nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

In 2020 I'll suggest you use ServletUriComponentsBuilder and it's static methods, such as ServletUriComponentsBuilder#fromCurrentRequest which helps you build your URL using the previous Request.

Example:

URL url = ServletUriComponentsBuilder
     .fromCurrentRequest()
     .path("/foo/bar.html")
     .encode() // To encode your url... always usefull
     .build()
     .toUri()
     .toURL()

Whatsmore, if you wanna redirect on the same app, please just return "redirect:/foo/bar.html" with status 302 and spring boot MVC will transform it into a normal redirection.

Example:

@ResponseBody
@GetMapping("/some/endpoint")
@ResponseStatus(HttpStatus.FOUND)
public ModelAndView redirectToFoo() {
   return new ModelAndView("redirect:/foo/bar.html");
}
Selast Lambou
  • 708
  • 12
  • 27