在 Spring MVC 中获取根/基 URL

发布于 2024-10-17 14:29:06 字数 221 浏览 6 评论 0原文

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

基本网址 = http://www.example.comhttp://www.example.com/VirtualDirectory

What is the best way to get the root/base url of a web application in Spring MVC?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

靖瑶 2024-10-24 14:29:06

我更喜欢使用

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

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

I prefer to use

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

It returns a completely built URL, scheme, server name and server port, rather than concatenating and replacing strings which is error prone.

妄司 2024-10-24 14:29:06

如果基本网址为“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();
}

来自 JSP:

在文档顶部声明此内容:

<c:set var="baseURL" value="${pageContext.request.localName}"/> //or ".localAddr"

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

<a href="http://${baseURL}">Go Home</a>

If base url is "http://www.example.com", then use the following to get the "www.example.com" part, without the "http://":

From a Controller:

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

From JSP:

Declare this on top of your document:

<c:set var="baseURL" value="${pageContext.request.localName}"/> //or ".localAddr"

Then, to use it, reference the variable:

<a href="http://${baseURL}">Go Home</a>
千秋岁 2024-10-24 14:29:06

解释

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

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

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request);

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

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

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null);

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"

添加

如果您想在控制器外部或没有 HttpServletRequest存在,你只需替换

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null)

ServletUriComponentsBuilder.fromCurrentContextPath()

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

Explanation

I know this question is quite old but it's the only one I found about this topic, so I'd like to share my approach for future visitors.

If you want to get the base URL from a WebRequest you can do the following:

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request);

This will give you the scheme ("http" or "https"), host ("example.com"), port ("8080") and the path ("/some/path"), while fromRequest(request) would give you the query parameters as well. But as we want to get the base URL only (scheme, host, port) we don't need the query params.

Now you can just delete the path with the following line:

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null);

TLDR

Finally our one-liner to get the base URL would look like this:

//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"

Addition

If you want to use this outside a controller or somewhere, where you don't have the HttpServletRequest present, you can just replace

ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request).replacePath(null)

with

ServletUriComponentsBuilder.fromCurrentContextPath()

This will obtain the HttpServletRequest through spring's RequestContextHolder. You also won't need the replacePath(null) as it's already only the scheme, host and port.

怪我闹别瞎闹 2024-10-24 14:29:06

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

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;

}

You can also create your own method to get it:

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;

}
拥抱影子 2024-10-24 14:29:06

简单地 :

/*
 * Returns the base URL from a request.
 *
 * @example: http://myhost:80/myapp
 * @example: https://mysecuredhost:443/
 */
String getBaseUrl(HttpServletRequest req) {
  return ""
    + req.getScheme() + "://"
    + req.getServerName()
    + ":" + req.getServerPort()
    + req.getContextPath();
}

Simply :

/*
 * Returns the base URL from a request.
 *
 * @example: http://myhost:80/myapp
 * @example: https://mysecuredhost:443/
 */
String getBaseUrl(HttpServletRequest req) {
  return ""
    + req.getScheme() + "://"
    + req.getServerName()
    + ":" + req.getServerPort()
    + req.getContextPath();
}
情绪少女 2024-10-24 14:29:06

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

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

各自安好 2024-10-24 14:29:06

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

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

In controller, use HttpServletRequest.getContextPath().

In JSP use Spring's tag library: or jstl

℉絮湮 2024-10-24 14:29:06

要么注入一个 UriCompoenentsBuilder:

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

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

// Get full URL (http://user:[email protected]/root/some?k=v#hey)
URI requestUri = new URI(req.getRequestURL().toString());
// and strip last parts (http://user:[email protected]/root)
URI contextUri = new URI(requestUri.getScheme(), 
                         requestUri.getAuthority(), 
                         req.getContextPath(), 
                         null, 
                         null);

然后您可以使用该 URI 中的 UriComponentsBuilder:

// http://user:[email protected]/root/some/other/14
URI complete = UriComponentsBuilder.fromUri(contextUri)
                                   .path("/some/other/{id}")
                                   .buildAndExpand(14)
                                   .toUri();

Either inject a UriCompoenentsBuilder:

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

. Or make it yourself (similar to Salims answer):

// Get full URL (http://user:[email protected]/root/some?k=v#hey)
URI requestUri = new URI(req.getRequestURL().toString());
// and strip last parts (http://user:[email protected]/root)
URI contextUri = new URI(requestUri.getScheme(), 
                         requestUri.getAuthority(), 
                         req.getContextPath(), 
                         null, 
                         null);

You can then use UriComponentsBuilder from that URI:

// http://user:[email protected]/root/some/other/14
URI complete = UriComponentsBuilder.fromUri(contextUri)
                                   .path("/some/other/{id}")
                                   .buildAndExpand(14)
                                   .toUri();
相守太难 2024-10-24 14:29:06

在JSP

<c:set var="scheme" value="${pageContext.request.scheme}"/>
<c:set var="serverPort" value="${pageContext.request.serverPort}"/>
<c:set var="port" value=":${serverPort}"/>

<a href="${scheme}://${pageContext.request.serverName}${port}">base url</a>

参考中 https://github.com/spring-projects/greenhouse/blob/master/src/main/webapp/WEB-INF/tags/urls/absoluteUrl.tag

In JSP

<c:set var="scheme" value="${pageContext.request.scheme}"/>
<c:set var="serverPort" value="${pageContext.request.serverPort}"/>
<c:set var="port" value=":${serverPort}"/>

<a href="${scheme}://${pageContext.request.serverName}${port}">base url</a>

reference https://github.com/spring-projects/greenhouse/blob/master/src/main/webapp/WEB-INF/tags/urls/absoluteUrl.tag

甚是思念 2024-10-24 14:29:06
     @RequestMapping(value="/myMapping",method = RequestMethod.POST)
      public ModelandView myAction(HttpServletRequest request){

       //then follow this answer to get your Root url
     }

servlet 的根 URl

如果您在 jsp 中需要它,请进入在控制器中并将其添加为 ModelAndView 中的对象。

或者,如果您在客户端需要它,请使用 javascript 来检索它:
http://www.gotknowhow.com/文章/如何使用 JavaScript 获取基址

     @RequestMapping(value="/myMapping",method = RequestMethod.POST)
      public ModelandView myAction(HttpServletRequest request){

       //then follow this answer to get your Root url
     }

Root URl of the servlet

If you need it in jsp then get in in controller and add it as object in ModelAndView.

Alternatively, if you need it in client side use javascript to retrieve it:
http://www.gotknowhow.com/articles/how-to-get-the-base-url-with-javascript

幸福还没到 2024-10-24 14:29:06

我认为这个问题的答案: 仅使用 ServletContext 查找应用程序的 URL 显示了为什么您应该使用相对 url,除非您有非常具体的原因需要根 url。

I think the answer to this question: Finding your application's URL with only a ServletContext shows why you should use relative url's instead, unless you have a very specific reason for wanting the root url.

夏有森光若流苏 2024-10-24 14:29:06

如果您只对浏览器中 url 的主机部分感兴趣,则直接从 request.getHeader("host")) -

import javax.servlet.http.HttpServletRequest;

@GetMapping("/host")
public String getHostName(HttpServletRequest request) {

     request.getLocalName() ; // it will return the hostname of the machine where server is running.

     request.getLocalName() ; // it will return the ip address of the machine where server is running.


    return request.getHeader("host"));

}

如果请求 url 是 https://localhost:8082/主机

localhost:8082

If you just interested in the host part of the url in the browser then directly from request.getHeader("host")) -

import javax.servlet.http.HttpServletRequest;

@GetMapping("/host")
public String getHostName(HttpServletRequest request) {

     request.getLocalName() ; // it will return the hostname of the machine where server is running.

     request.getLocalName() ; // it will return the ip address of the machine where server is running.


    return request.getHeader("host"));

}

If the request url is https://localhost:8082/host

localhost:8082

×纯※雪 2024-10-24 14:29:06

此处:

在您的 .jsp 文件中的 [body 标记]

在您的 .js 文件中

var baseUrl = windowurl.split('://')[1].split('/')[0]; //as to split function 
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/your url in your controller';
xhr.open("POST", url); //using "POST" request coz that's what i was tryna do
xhr.send(); //object use to send```

Here:

In your .jsp file inside the [body tag]

<input type="hidden" id="baseurl" name="baseurl" value=" " />

In your .js file

var baseUrl = windowurl.split('://')[1].split('/')[0]; //as to split function 
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/your url in your controller';
xhr.open("POST", url); //using "POST" request coz that's what i was tryna do
xhr.send(); //object use to send```
亽野灬性zι浪 2024-10-24 14:29:06

我有确切的要求并达到了以下解决方案:

String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .replacePath(null).replaceQuery(null).fragment(null).build().toUriString();

为了使此代码正常工作,它应该在绑定到 Servlet 请求的线程内运行。

I had the exact requirement and reached to below solution:

String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .replacePath(null).replaceQuery(null).fragment(null).build().toUriString();

For this code to work, it should run inside a thread bound to a Servlet request.

秋日私语 2024-10-24 14:29:06

以下内容对我有用:

在控制器方法中,添加 HttpServletRequest 类型的参数。您可以拥有此参数,并且仍然拥有 @RequestBody 参数,这是之前所有答案都没有提到的。

@PostMapping ("/your_endpoint")
public ResponseEntity<Object> register(
   HttpServletRequest servletRequest,
   @RequestBody RegisterRequest request
) {

    String url = servletRequest.getRequestURL().toString();
    String contextPath = servletRequest.getRequestURI();
    String baseURL = url.replace(contextPath,"");

    /// .... Other code 

}

我在 Spring Boot 3.0.6 上对此进行了测试。

The following worked for me:

In the controller method, add a parameter of type HttpServletRequest. You can have this parameter and still have an @RequestBody parameter, which is what all the previous answers fail to mention.

@PostMapping ("/your_endpoint")
public ResponseEntity<Object> register(
   HttpServletRequest servletRequest,
   @RequestBody RegisterRequest request
) {

    String url = servletRequest.getRequestURL().toString();
    String contextPath = servletRequest.getRequestURI();
    String baseURL = url.replace(contextPath,"");

    /// .... Other code 

}

I tested this on Spring Boot 3.0.6.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文