简体   繁体   English

在Spring MVC中生成路由的推荐方法有哪些?

[英]What are the recommended approaches for generating routes in Spring MVC?

What are the recommended approaches for generating routes in a java-based Spring MVC webapp? 在基于java的Spring MVC webapp中生成路由的推荐方法是什么? I'd like to avoid hard-coding paths throughout the application. 我想避免在整个应用程序中使用硬编码路径。

Assuming we are talking about paths RequestMappings etc. In my application I have a single class with with a bunch of public static final constants that I reference in the @RequestMapping annotations. 假设我们正在讨论路径RequestMappings等。在我的应用程序中,我有一个带有一堆public static final常量的类,我在@RequestMapping注释中引用它们。

So the constants might look like this: 因此常量可能如下所示:

public class Pages {
  public static final String FOO_URL "foo/foo.action"
  public static final String FOO_VIEW "test/foo"

  public static final String BAR_URL "bar/bar.action"
  public static final String BAR_VIEW "test/bar"
}

then inside your controller you'd reference them like this: 然后在你的控制器内你会像这样引用它们:

@RequestMapping(value=Pages.FOO_URL, method=RequestMethod.GET)
public String handleFoo(Model model) {
      return Pages.FOO_VIEW;
    }

They're easy to change as they're all in one place. 它们很容易改变,因为它们都在一个地方。

You say you'd like to avoid hard-coding paths throughout the application, but typically all the controllers (and thus all the url mappings) reside in one directory. 您说您希望避免整个应用程序中的硬编码路径,但通常所有控制器(以及所有url映射)都驻留在一个目录中。 For example if you have a maven structure they'll be someplace like src/main/java/com/mycompany/myapp/web/controllers/. 例如,如果你有一个maven结构,他们就会像src / main / java / com / mycompany / myapp / web / controllers /那样。 Do you envision yourself ever asking the question, "Just where did I put the url mapping for the /myapp/v1/search endpoint?", and not being able to figure out that it's in /src/main/java/com/mycompany/myapp/web/controllers/V1SearchController.java? 您是否想过自己曾经问过这样一个问题:“我在哪里为/ myapp / v1 /搜索端点设置了url映射?”,并且无法弄清楚它位于/ src / main / java / com / mycompany中/myapp/web/controllers/V1SearchController.java?

Also once you choose the urls they're pretty much fixed since they represent an interface with clients, and changing them probably means breaking backward compatibility. 此外,一旦您选择了网址,它们就会被修复,因为它们代表了与客户端的接口,而更改它们可能意味着破坏向后兼容性。

Not that I think a class with a bunch of static final Strings is all that bad, I just think it's mostly unnecessary. 并不是说我认为一个带有一堆静态最终字符串的课程就是那么糟糕,我只是觉得它几乎没必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM