【问题标题】:Get Root/Base Url In Spring MVC在 Spring MVC 中获取根/基 URL
【发布时间】:2011-06-28 02:31:25
【问题描述】:

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

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

【问题讨论】:

  • 你在哪里需要这个?在控制器中还是在 JSP 页面中?
  • 网站中可以访问竞赛/请求/响应以获取它的任何地方。
  • ServletUriComponentsBuilder.fromCurrentServletMapping().toUriString()

标签: spring-mvc base-url


【解决方案1】:

简单地说:

/*
 * 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();
}

【讨论】:

  • 世界上最好的答案。
  • 非常棒的答案
【解决方案2】:

这里:

在 [body 标签] 内的 .jsp 文件中

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

在您的 .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```

【讨论】:

【解决方案3】:

如果您只是对浏览器中 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/host

本地主机:8082

【讨论】:

    【解决方案4】:

    说明

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

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

    ServletUriComponentsBuilder.fromRequestUri(HttpServletRequest request);
    

    这将为您提供方案(“http”或“https”)、主机(“example.com”)、端口(“8080”)和路径(“/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),因为它已经只有方案、主机和端口。

    【讨论】:

    • 不幸的是,这只适用于 bean 或控制器。搜索在生成的 PDF 中添加应用程序服务器 URL 的解决方案将近 2 天,没有运气:( 在 controllersbeans 之外获取 java.lang.IllegalStateException: No current ServletRequestAttributes
    【解决方案5】:

    我更喜欢使用

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

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

    【讨论】:

    • 我一直在寻找这个,因为它可以在任何地方使用,甚至在应用启动时。
    • 这就是我要找的东西!
    • 它不起作用:java.lang.IllegalStateException: 没有当前的 ServletRequestAttributes 我在 @EventListener(ApplicationReadyEvent.class) 处理程序中使用它,尝试使用应用程序基本 url 来做某事,但它没有工作。 SpringBoot 2.1.7
    • 这里也一样,除了控制器之外,我在任何地方都会收到该错误。我认为它需要一个请求上下文才能工作。
    【解决方案6】:

    在 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

    【讨论】:

      【解决方案7】:

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

      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;
      
      }
      

      【讨论】:

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

      要么注入UriCompoenentsBuilder

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

      。或者自己制作(类似于 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);
      

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

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

      【讨论】:

      • 感谢UriComponentBuilder 的介绍 - 我以前从未使用过它。非常有用。
      • 没问题,很高兴能帮上忙。
      【解决方案9】:

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

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

      【讨论】:

        【解决方案10】:

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

        【讨论】:

        【解决方案11】:

        如果基本 url 是“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>
        

        【讨论】:

        • 或者,在 JSP 中,您可以使用 "http://" 前缀直接设置“baseURL”变量的值
        • HttpServletRequest 类型的方法 getLocalAddr() 未定义
        • Tbh 你不应该使用它,因为它是一个相当古老的答案并且不再是最新的。看看我的回答stackoverflow.com/questions/5012525/…
        【解决方案12】:

        我认为这个问题的答案:Finding your application's URL with only a ServletContext 说明了为什么您应该使用相对 url,除非您有非常具体的原因需要根 url。

        【讨论】:

          【解决方案13】:
               @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

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

          或者,如果您在客户端需要它,请使用 javascript 来检索它: http://www.gotknowhow.com/articles/how-to-get-the-base-url-with-javascript

          【讨论】:

          猜你喜欢
          • 2011-08-01
          • 2012-08-25
          • 1970-01-01
          • 2011-03-06
          • 1970-01-01
          • 2014-06-21
          • 1970-01-01
          • 2016-07-13
          • 1970-01-01
          相关资源
          最近更新 更多