【问题标题】:Logic block in Grails URLMappingsGrails URLMappings 中的逻辑块
【发布时间】:2012-03-01 22:28:14
【问题描述】:

我的网站有类似“http://someRandomUsername.mysite.com”的网址。 有时用户会尝试像这样的网址 'http://www.someRandomeUsername.mysite.com'。我想要一些 我的 url 映射中的逻辑来处理这个问题。 当我点击页面时,使用下面的映射,有或没有 不需要的 www,我得到:

2012-03-01 14:52:16,014 [http-8080-5] 错误 [localhost].[/ambit] - 装饰页面时发生未处理的异常 java.lang.IllegalArgumentException:URL 映射必须提供一个 要映射到的控制器或视图名称!

知道如何做到这一点吗?映射如下。

谢谢! 杰森

静态映射 = {

         name publicMap: "/$action?/$id?" {
                 def ret = UrlMappings.check(request)
                 controller = ret.controller
                 userName = ret.userName
         }
}

static check =
{ request ->
         def tokens = request?.serverName?.split(/\./) as List ?: []
         def ret = [controller:'info']
         if(tokens.size() > 3 && token[0] == 'www')
         {
                 ret.userName = tokens[1]
                 ret.controller = 'redirect'
                 ret.action = 'removeWWW'
         }
         else if(tokens.size() == 3)
         {
                 ret.userName = tokens[0]
                 ret.controller = 'info'
         }

         return ret
}

【问题讨论】:

  • 冬青通心粉!为什么这是必要的?为什么不将 url 重定向/重写委托给 Apache?
  • 这里没有使用Apache。

标签: grails groovy urlmappings.groovy


【解决方案1】:

老实说,正如 DmitryB 所说,最好的方法是通过 Web 服务器,无论是 IIS、Apache 还是 Tomcat。

话虽如此,我觉得在 Grails 中实现这一点的最佳方法是使用过滤器。 您可以在 ~/conf 目录中创建类似的内容:

public class StripFilters {
  def filters = {
    stripWWWFilter(controller: '*', action: '*') {
      before = {
        def tokens = request.serverName.tokenize(/\./) ?: []

        if(tokens.size() > 3 && tokens[0] == 'www') {
          def url = request.request.requestURL.toString().replace('www.', '')
          redirect([url:url, params: [userName: tokens[1]], permanent: true])
          return false
        }
      }
    }
  }
}

这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多