0

I've spent a few days researching this, but haven't found a suitable answer for my situation. I have a Spring 3.1 MVC application. Currently, some vendors log into the application via a web client in which case the user information is stored in the session. I want to expose some services to other vendors via RESTFul web services, but have the vendor pass their vendor id as a part of the URI or via PARAMS. Is there a way to handle the vendor id in a single place that then forwards to the respective controller for request processing? Should the vendor id be a part of the URI or should the vendor id be passed in the request body? I've looked into Interceptors, but how would I do this with multiple URIs or for every controller for the RESTFul webservice? Any suggestion would be greatly appreciated

4

2 回答 2

1

拥有自定义标题是最简洁的选项,但参数也同样适用。在拦截器的preHandle方法中,您可以通过标头或参数查找供应商,并通过将对象添加到其属性将其附加到请求中。

request.addAttribute("vendor", myVendorInstance);

从那时起,vendor可以从请求中检索,例如:

Vendor vendor = (Vendor) request.getAttribute("vendor");

拦截器可以使用映射映射到您喜欢的任何 URL,例如

<mvc:interceptor>
    <mvc:mapping path="/vendors/**" />
    <bean class="my.package.VendorLookupInterceptor" />
</mvc:interceptor>

使控制器可以使用 vendor 对象的另一种方法是注入它。例如,假设对对象感兴趣的控制器应该实现这个接口。

public interface VendorAware {
    public void setVendor(Vendor vendor);
}

实现此接口的控制器可以由拦截器处理并注入供应商。

if (handler instanceof HandlerMethod) {
    Object bean = ((HandlerMethod) handler).getBean();

    if (bean instanceof VendorAware) {
        Vendor vendor = getVendor();
        ((VendorAware) bean).setVendor(vendor);
    }
}
于 2013-07-28T07:35:35.147 回答
0

显然,将供应商 ID 添加到 URI 的问题在于它会影响您的所有 URL,因此不能轻易地使控制器通用。另一种方法是将供应商 ID 作为标头传递给控制器​​。您可以使用 X-User 标头。

然后您可以编写某种处理程序来检查此标头,可能性:

  • 弹簧拦截器
  • 小服务程序过滤器
  • 春季安全
  • 方面j
于 2013-07-27T18:59:37.993 回答