具有spring mvc的多个域 [英] Multiple domains with spring mvc
问题描述
假设我有一个应用程序必须缩短URL,但也做其他事情。 (例如 google.com
和 goo.gl
,或 facebook.com
和 fb.me
)。
Let's say I have an application that has to shorten URLs, but also do other things. (like google.com
and goo.gl
, or facebook.com
and fb.me
).
简单地部署两个应用程序很简单,但是(对于现在)成为一个人更简单。使用spring和spring-mvc。我有以下映射:
It will be easy to simply deploy two applications, but (for now) it's simpler to be just one. Using spring and spring-mvc. I have the following mappings:
@RequestMapping(value="/{shortUrlKey}", headers="Host=foo.br")
...
@RequestMapping(value="/{username}")
唉,标题
注释不是提供更具体的信息,而是作为限制。所以如果我有这两个,只有后者被调用,即使我打开它作为 http://foo.br/asdf
。如果只留下前者,它适用于来自 foo.br
的那些,并且如果主机不同则不会打开任何内容。
Alas, the headers
annotation acts not as giving more specific information, but as restricting instead. So if I have these two, only the latter is invoked, even if I open it as http://foo.br/asdf
. If leave only the former, it works for those coming from foo.br
, and doesn't open anything if the host is different.
所以,问题:
- 如何为相同的路径制作两个处理程序,但不同的URL /主机
- 是否可以使用属性占位符配置器动态解析主机(而不是在注释中对其进行硬编码)
如果有一些可插拔的方法解析机制,也许两者都可以。有这样的吗?
Perhaps both would work if there is some pluggable mechanism for method resolution. Is there such?
推荐答案
我的直接建议是写一个servlet过滤器(或一个Spring HandlerInterceptor
),它将从请求中获取主机名,将其添加到原始请求的路径,然后转发请求。
My immediate suggestion would be to write a servlet filter (or a Spring HandlerInterceptor
), which would take the host name from the request, prepend it to the original requested path, then forward on the request.
例如,根据请求的URL http://goo.gl/my/path ,过滤器将转发到 /goo.gl/my/path
。然后,Spring MVC映射就可以获得一些东西。 ant样式通配符语法(例如** / my / path
)或路径变量样式(例如{requestHost} / my /路径
可能会有所帮助。
For example, given the requested URL http://goo.gl/my/path, the filter would forward to /goo.gl/my/path
. The Spring MVC mappings would then have something to get their teeth into. The ant-style wildcard syntax (e.g. "**/my/path"
) or path-variable style (e.g. "{requestHost}/my/path"
might be helpful there.
或者,过滤器可以设置包含所请求主机的自定义标头或请求属性,但这可能更少灵活。
Alternatively, the filter could set a custom header or request attribute containing the requested host, but that's probably less flexible.
我不确定你的问题的第二部分是什么意思。
I'm not sure what you mean by the second part of your question, though.
这是一个工作片段:
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURL().toString().contains(shortenerDomain)
&& !request.getRequestURI().startsWith(SHORT_URI_PREFIX)) {
request.getRequestDispatcher(SHORT_URI_PREFIX + request.getRequestURI())
.forward(request, response);
return false;
} else {
return true;
}
}
这篇关于具有spring mvc的多个域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!