java - 在 Play 2 中使用 anchor 重定向

标签 java playframework-2.0

我正在寻找将 anchor 添加到 Controller 中返回的 url 的可能性:

public static Result open(String id) {
  // here I want to add acnhor like #foo to the produced url
  return redirect(routes.MyPage.show(id));
}

found在 play 1 中使用 addRef 方法是可能的,但我在 play 2 中找不到该方法的任何替代方法。

当然我可以像这样使用连接:

public static Result open(String id) {
  // here I want to add acnhor like #foo to the produced url
  return redirect(routes.MyPage.show(id).url + "#foo");
}

但是看起来很丑。

感谢您的帮助!祝你有美好的一天!

最佳答案

在尝试回答该问题之前。 我应该建议您更改当前设置的任何行为。

因为,URL 片段的目的只是客户端。这样的片段永远不会发送到服务器,因此做相反的事情很麻烦。

但是,这是您可以遵循的(相当?)优雅解决方案的雏形。

我将尝试做的是让浏览器处理片段,以保留潜在的行为(例如转到 ID 甚至处理历史...)。

为此,您可以在 main 模板中添加一个 implicit 参数,它将定义 URL 应具有的片段:

@(title: String)(content: Html)(urlFragment:Option[UrlFragment] = None)

如您所见,我将参数包装在 Option 中并将其默认设置为 None(以避免 AMAP 污染)。

此外,它只是包装了一个 String,但您可以单独使用 String —— 使用专用类型将强制执行语义。这是定义:

case class UrlFragment(hash:String)

非常简单。

现在这里是如何告诉浏览器去处理它。在 head 元素末尾和 body 开始之前,只需添加以下内容:

@urlFragment.map { f =>
  <script>
    $(function() {
      //after everything is ready, so that other mechanism will be able to use the change hash event...
      document.location.hash = "@Html(@f.hash)";
    });
  </script>
}

如您所见,使用 map(即当 urlFragment 不是 None 时)我们添加一个脚本 block 来设置散列在 urlFragment 中可用。

这可能是一个开始,但是......为整个场景考虑另一种解决方案。

关于java - 在 Play 2 中使用 anchor 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055010/

相关文章:

java - android 到 sqlserver 的连接字符串

java - 如何在 Java 中引用匿名或嵌套类的包含类

scala - 使用 sass 和 compass 配置文件玩框架 2

playframework-2.0 - 使用 Jackson Json Views 注释方法 Play Framework 2

playframework - Play Framework 项目推荐结构

java - 暴乱异常 : No dataset writer for RDF/XML/pretty

java - 如何添加两个不同类的 ArrayList,将一个抽象类扩展到一个 ArrayList 中?

java - 以挂起状态启动camunda进程

sql - 使用 Anorm 和 Scala Play 框架的动态 SQL 参数

playframework - 如何在 Play 2.0 中以编程方式更新 Play.configuration?