【问题标题】:Generating URL for Controller action in Spring在 Spring 中为 Controller 操作生成 URL
【发布时间】:2017-12-07 09:17:40
【问题描述】:

如何为控制器操作动态创建 URL?

考虑以下情况:

@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method() {
        return "Whatever"
    }
}

我想做的是获取基本 URL 并将控制器 / url 连接到它。 对于这种行为,例如 Laravel 提供了 URL 助手(action() 方法)。 Spring Boot中是否有类似的东西?

【问题讨论】:

  • 你能用例子详细说明一下吗
  • 你能看看我的回答吗?

标签: java spring spring-mvc spring-boot


【解决方案1】:

您可以使用UriComponentsBuilder 获取当前网址并将附加部分连接到该网址

@Controller
@RequestMapping("controller")
public class Controller {
    @RequestMapping("url")
    public String method(UriComponentBuilder ucb) {
        URI uri = ucb.path("/url").build().toUri();
        return "Whatever"
    }
}

【讨论】:

  • 我需要在那个控制器之外生成那个 URL。
  • 你的意思是,在映射请求的任何方法之外?
  • 要将请求映射到某处,您需要知道某处的位置。该位置是 URL,因此我希望能够生成某处的 URL。
  • 是的,应用程序必须至少有一个已知映射。一旦请求到达那里,您可以简单地使用return "redirect:/user?url=website.com" 通过传递任何请求参数/路径变量将其传递给任何其他控制器方法。除非您传递给不同的应用程序,否则您实际上并不需要完整的 url。如果您在同一个应用程序中重定向它,相对路径就足够了。
  • 是的,但这意味着我必须记住给定的控制器是否具有特殊的 URL 映射。
【解决方案2】:

有一个用于 Spring Boot 框架的库。您需要在项目中添加以动态生成链接。下面给出这个库的gradle依赖。

compile 'org.springframework.boot:spring-boot-starter-hateoas:2.1.4.RELEASE'

我假设您的构建系统是 gradle,但如果您使用的是 maven,请使用以下语法。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

之后,您可以如下动态生成链接。

WebMvcLinkBuilder.linkTo(Controller.class).slash("url").withSelfRel().getHref();

【讨论】:

    【解决方案3】:

    我认为使用@PathVariable 会帮助你

    @Controller
    @RequestMapping(value="/controller")
    public class Controller {
        @RequestMapping(value="/url/{id}", method=RequestMethod.GET)
        public String method(@PathVariable("id") String id) {
             System.out.println("the url value : "+id );
            return "Whatever"
        }
    }
    

    然后您可以使用 /controller/url/{here the value} 调用该方法 例如 /controller/url/www.google.com

    【讨论】:

    • 这不是我要问的。
    【解决方案4】:

    如果您只想映射 Controller ,请使用属性文件

    application.properties

    server.context-path=/rest
    

    如果您的控制器从存储库提供数据,那么 Spring Data REST 可以消除大部分样板文件并解决您最初的问题。

    Spring Data REST

    pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    

    您可以使用属性文件来控制基本 URL。

    application.properties

    spring.data.rest.basePath=/rest
    

    这就是你想要的 /rest concat controller/url

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      相关资源
      最近更新 更多