【问题标题】:Getting the URL of the current page in Grails在 Grails 中获取当前页面的 URL
【发布时间】:2010-11-26 21:52:30
【问题描述】:

在 Grails 应用程序中,我想将用户从页面 A 发送到页面 B 上的表单,然后再次返回页面 A。

为了跟踪要返回的 URL,我向页面 B 发送了一个“returnPage”参数,其中包含要返回的页面的 URL(页面 A)。

目前我在页面 A 上使用 request.getRequestURL() 来检索页面的 URL。但是,我从 getRequestURL() 获得的 URL 与最终用户在他/她的地址栏中的 URL 不对应:

request.getRequestURL() == "http://localhost:8080/something/WEB-INF/grails-app/views/layouts/main.gsp"
URL in address bar == "http://localhost:8080/something/some/thing"

如何获取“最终用户”URL?

【问题讨论】:

    标签: grails


    【解决方案1】:

    答案是request.forwardURI (details here)。

    【讨论】:

    【解决方案2】:

    我构建了这个方法来获取当前的 url。

    static String getCurrentUrl(HttpServletRequest request){
    
        StringBuilder sb = new StringBuilder()
    
        sb << request.getRequestURL().substring(0,request.getRequestURL().indexOf("/", 8))
    
        sb << request.getAttribute("javax.servlet.forward.request_uri")
    
        if(request.getAttribute("javax.servlet.forward.query_string")){
    
            sb << "?"
    
            sb << request.getAttribute("javax.servlet.forward.query_string")
        }
    
        return sb.toString();
    }
    

    【讨论】:

    • 不用去javax属性,你可以用request.forwardURI得到同样的结果
    • 如果网站使用 https,fromIndex 需要从 7 改为 8。
    【解决方案3】:

    我更喜欢使用:

    createLink(action: "index", controller:"user", absolute: true)
    // http://localhost:8080/project/user
    

    当我需要获取绝对网址时!

    获取相对路径也很有趣:

    createLink(action: "index", controller:"user")
    // /project/user
    

    【讨论】:

      【解决方案4】:

      在创建到页面 B 的链接时,您可以使用 createLink 标签设置 returnPage 参数:

      <g:link controller="pageB" 
              action="someaction" 
              params='[returnPage:createLink(action:actionName, params:params)]'>
        Go to Page B
      </g:link>
      

      【讨论】:

      • 这完全忽略了 URI 中的参数。
      【解决方案5】:

      我的解决方案(Grails 1.3.7)是这个,您可以将其复制并粘贴到您的控制器中:

      boolean includePort = true;
      String scheme = request.getScheme();
      String serverName = request.getServerName();
      int serverPort = (new org.springframework.security.web.PortResolverImpl()).getServerPort(request)
      String contextPath = request.getContextPath();
      boolean inHttp = "http".equals(scheme.toLowerCase());
      boolean inHttps = "https".equals(scheme.toLowerCase());
      
      if (inHttp && (serverPort == 80)) {
          includePort = false;
      } else if (inHttps && (serverPort == 443)) {
          includePort = false;
      }
      String redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
      

      在我们的应用程序中,我们不能只使用g.createLink(.. absolute:true),因为我们有不同的最终用户 URL,因为有多个客户。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 2016-03-01
        • 2015-09-30
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多