在Spring MVC中获取Root/Base Url

Mik*_*ynn 26 spring-mvc base-url

在Spring MVC中获取Web应用程序的根/基本URL的最佳方法是什么?

Base Url = http://www.example.comhttp://www.example.com/VirtualDirectory

Nah*_*ahn 25

如果基本网址是" http://www.example.com ",则使用以下内容获取" www.example.com "部分,而不使用"http://":

来自控制器:

@RequestMapping(value = "/someURL", method = RequestMethod.GET)
public ModelAndView doSomething(HttpServletRequest request) throws IOException{
    //Try this:
    request.getLocalName(); 
    // or this
    request.getLocalAddr();
}
Run Code Online (Sandbox Code Playgroud)

来自JSP:

在您的文档顶部声明:

<c:set var="baseURL" value="${pageContext.request.localName}"/> //or ".localAddr"
Run Code Online (Sandbox Code Playgroud)

然后,要使用它,请引用变量:

<a href="http://${baseURL}">Go Home</a>
Run Code Online (Sandbox Code Playgroud)


nxh*_*oaf 17

您还可以创建自己的方法来获取它:

public String getURLBase(HttpServletRequest request) throws MalformedURLException {

    URL requestURL = new URL(request.getRequestURL().toString());
    String port = requestURL.getPort() == -1 ? "" : ":" + requestURL.getPort();
    return requestURL.getProtocol() + "://" + requestURL.getHost() + port;

}
Run Code Online (Sandbox Code Playgroud)

  • 这样做的问题是 URL 是从请求中获取的。这意味着,如果为 *.example.com 签名的证书(解析为 192.168.42.1)并且使用 IP 地址而不是名称发出请求,则会导致问题。最好的方法是在应用程序配置中的某个位置配置(硬编码)名称。这样,当发送电子邮件等内容时,您的电子邮件将更加合法和可信。 (2认同)

Mir*_*ndt 13

解释

我知道这个问题已经很老了,但它是我发现的唯一一个关于这个主题的问题,所以我想与未来的访问者分享我的方法。

如果要从 WebRequest 获取基本 URL,可以执行以下操作:

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request);
Run Code Online (Sandbox Code Playgroud)

这将为您提供方案(“http”或“https”)、主机(“example.com”)、端口(“8080”)和路径(“/some/path”),同时fromRequest(request)将为您提供查询参数以及。但由于我们只想获取基本 URL(方案、主机、端口),因此我们不需要查询参数。

现在您可以使用以下行删除路径:

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null);
Run Code Online (Sandbox Code Playgroud)

TLDR

最后,我们获取基本 URL 的单行代码如下所示:

//request URL: "http://example.com:8080/some/path?someParam=42"

String baseUrl = ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request)
        .replacePath(null)
        .build()
        .toUriString();

//baseUrl: "http://example.com:8080"
Run Code Online (Sandbox Code Playgroud)

添加

如果你想在控制器之外或其他地方使用它,你没有HttpServletRequest礼物,你可以更换

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null)
Run Code Online (Sandbox Code Playgroud)

ServletUriComponentsBuilder.fromCurrentContextPath()
Run Code Online (Sandbox Code Playgroud)

这将获得HttpServletRequest通过 spring 的RequestContextHolder. 您也不需要 ,replacePath(null)因为它已经只有方案、主机和端口。


Eno*_*ong 12

我更喜欢使用

final String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();

它返回一个完整构建的URL,方案,服务器名称和服务器端口,而不是连接和替换容易出错的字符串。

  • 我一直在寻找这个,因为它可以在任何地方使用,甚至在应用程序启动时也是如此。 (3认同)
  • 它不起作用: java.lang.IllegalStateException: No current ServletRequestAttributes 我在 @EventListener(ApplicationReadyEvent.class) 处理程序中使用它,尝试使用应用程序基本 url 进行某些操作,但它不起作用。SpringBoot 2.1.7 (3认同)

Sal*_*idi 11

request.getRequestURL().toString().replace(request.getRequestURI(),request.getContextPath())


Win*_*ins 9

在控制器中,使用HttpServletRequest.getContextPath().

在JSP中使用Spring的标记库:或jstl


Kar*_*l.S 9

简单地 :

String getBaseUrl(HttpServletRequest req) {
    return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*ing 6

要么注入UriCompoenentsBuilder

@RequestMapping(yaddie yadda)
public void doit(UriComponentBuilder b) {
  //b is pre-populated with context URI here
}
Run Code Online (Sandbox Code Playgroud)

。或者自己动手制作(类似于Salims的答案):

// Get full URL (http://user:pwd@www.example.com/root/some?k=v#hey)
URI requestUri = new URI(req.getRequestURL().toString());
// and strip last parts (http://user:pwd@www.example.com/root)
URI contextUri = new URI(requestUri.getScheme(), 
                         requestUri.getAuthority(), 
                         req.getContextPath(), 
                         null, 
                         null);
Run Code Online (Sandbox Code Playgroud)

然后,您可以从该URI使用UriComponentsBuilder:

// http://user:pwd@www.example.com/root/some/other/14
URI complete = UriComponentsBuilder.fromUri(contextUri)
                                   .path("/some/other/{id}")
                                   .buildAndExpand(14)
                                   .toUri();
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

76231 次

最近记录:

6 年 前