简体   繁体   English

在Spring中创建URL的最佳方法

[英]Best approach for creating URLs in Spring

Let's say we have controllers with URL mappings like movie/{id}-{title} , actor/{id}-{name} , etc. These mappings identify some objects in our app, mostly entities - we can say it's a RESTful service. 假设我们有带有URL映射的控制器,例如movie/{id}-{title}actor/{id}-{name}等。这些映射标识了我们应用中的某些对象,主要是实体-我们可以说这是RESTful服务。

I'm looking for a solution as to where I should put methods responsible for creation of those URIs. 我正在寻找一种解决方案,该将那些负责创建这些URI的方法放在哪里。 I think that creating them in multiple JSP files and some other places (redirection, etc.) is redundant. 我认为在多个JSP文件和其他一些地方(重定向等)中创建它们是多余的。

First, what I thought about was creating some interface with method public URI getURI() that classes that will be used in controllers will implement. 首先,我想到的是使用方法public URI getURI()创建一些接口,该接口将在控制器中使用。 But, in my opinion, that would involve too much into entity - I prefer entities just to represent data and contain only methods to change state. 但是,在我看来,这将对实体产生太多影响-我更喜欢实体仅代表数据并且仅包含更改状态的方法。

My second idea was to create a URIService with overloaded methods like URI getURI(Movie m) and URI getURI(Actor a) , but there will be a problem with the choice of overloading method at compile time. 我的第二个想法是创建一个URIService具有重载方法,比如URI getURI(Movie m)URI getURI(Actor a) ,但会有在编译时重载方法的选择问题。 For example, in EL in JSP that wouldn't work well, as the solution would be naming methods differently. 例如,在JSP中的EL中效果不佳,因为解决方案将以不同的方式命名方法。

I don't want to reinvent the wheel, so maybe you know or use some solution to that problem? 我不想重新发明轮子,所以也许您知道或使用某些解决方案来解决这个问题?

How enterprisey do you want the solution to be? 您希望解决方案的企业精神如何? (I'm just half kidding) (我只是在开玩笑)

Here's a solution: Have a service that has a method like URI getURI(Object o) . 这是一个解决方案:拥有一个具有URI getURI(Object o)类的方法的服务。 This method will check if the object passed belongs to a class with an annotation that specifies the URI path. 此方法将检查传递的对象是否属于带有指定URI路径的注释的类。 Example annotation: 注释示例:

public @interface PathTemplate {String value();}

Example class with the annotation: 带有注释的示例类:

@PathTemplate("/movie/{title}-{id}")
public class Movie {
  private int id;private String title;
  // getters and setters too
}

Now, the getURI method will see that the parameter object's class has a PathTemplate annotation and will interpolate the parameters using bean introspection. 现在, getURI方法将看到参数对象的类具有PathTemplate批注,并将使用bean内省法对参数进行插值。 Voila! 瞧! Expandable and relatively decoupled URI generation. 可扩展且相对分离的URI生成。

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

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