2


我们有一种情况,我们让我们的营销网站的超级用户能够直接搜索带有 slug 的产品。他们点击的链接重定向到该产品的实际页面。这适用于英语语言环境。但是,在 slug 已本地化的非英语语言环境中,重定向会导致所有重音字符被替换为“?”。

例如,http ://domain.xx.be/fr/category /catégorie/product_name重定向到http://domain.xx.be/fr/category/cat?gorie/product_name,它会给出 404。

有没有办法在使用 play mvc Results api 时保留重定向 url 中的重音字符。
PS 我们将绝对重定向 url 作为来自不同 API 的 json 响应的一部分。

编辑:为清楚起见添加一些代码

def getProductPage(slug: String, locale: String) = AsyncAction {
  flow {
    val response = gateway.getPathBySlug(slug, locale).!
    val url = (response.json \ "url").as[String]
    MovedPermanently(url)
  } recover {
    case ex => throw ex
  }
}
4

2 回答 2

1

你需要玩一点编码,在 Java 中它适用于我:

public static Result bad() {
    return temporaryRedirect("http://fr.wikipedia.org/wiki/Catégorie");
}

public static Result good() {
    return temporaryRedirect(encodeUrl("http://fr.wikipedia.org/wiki/Catégorie"));
}

public static String encodeUrl(String url) {
    try {
        url = URLEncoder.encode(url.trim(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return url
            .replace("%20", "_")
            .replace("%21", "!")
            .replace("%22", "'") // single quotas
            .replace("%24", "$")
            .replace("%27", "'")
            .replace("%28", "(")
            .replace("%29", ")")
            .replace("%2C", ",")
            .replace("%2F", "/")
            .replace("%3A", ":")
            .replace("%3F", "_") // question sign
            .replace("%E2%80%9E", "'") // lower quotas
            .replace("%E2%80%9D", "'") // upper quotas
            .replace("+", "_")
            .replace("%25", "percent");
}

它将特殊重音字符编码为 URL 实体,但毕竟使常见的 URL 字符重新生效

于 2013-11-04T15:23:33.373 回答
0

java.net.URI#toASCIIString救援。

文档

将此 URI 的内容作为字符串返回。

如果此 URI 是通过调用此类中的一个构造函数来创建的,则返回与原始输入字符串或从原始给定组件计算的字符串等效的字符串(视情况而定)。否则,此 URI 是通过规范化、解析或相对化创建的,因此根据 RFC 2396 第 5.2 节第 7 步中指定的规则从此 URI 的组件构造一个字符串。

所以你的代码变成

def getProductPage(slug: String, locale: String) = AsyncAction {
  flow {
    val response = gateway.getPathBySlug(slug, locale).!
    val url = (response.json \ "url").as[String]
    val encodedDestination = new URI(url).toASCIIString
    MovedPermanently(encodedDestination)
  } recover {
    case ex => throw ex
  }
}
于 2014-05-09T06:11:52.247 回答