DispatchAsync больше не генерируется путем отложенного связывания. Таким образом, вы не можете использовать GWT.create для его создания.
GWTP Dispatch интенсивно использует GIN/Guice. Поэтому я бы порекомендовал вам использовать эту инфраструктуру инъекций зависимостей для работы GWTP Dispatch.
Вот пример, который обеспечивает легкий доступ к DispatchAsync (без необходимости переписывать все страницы, чтобы использовать шаблон GWTP MVP):
[Примечание: В этом примере используется gwtp направить 1.0.3]
Клиент:
MyClientModule.java - настройка нагнетательных-правила для DispatchAsync
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.gwtplatform.dispatch.client.DefaultExceptionHandler;
import com.gwtplatform.dispatch.client.DefaultSecurityCookieAccessor;
import com.gwtplatform.dispatch.client.ExceptionHandler;
import com.gwtplatform.dispatch.client.RpcDispatchAsync;
import com.gwtplatform.dispatch.client.actionhandler.ClientActionHandlerRegistry;
import com.gwtplatform.dispatch.client.actionhandler.DefaultClientActionHandlerRegistry;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.dispatch.shared.SecurityCookie;
import com.gwtplatform.dispatch.shared.SecurityCookieAccessor;
public class MyClientModule extends AbstractGinModule {
private static final String COOKIE_NAME = "JSESSIONID";
@Override
protected void configure() {
bindConstant().annotatedWith(SecurityCookie.class).to(COOKIE_NAME);
bind(ExceptionHandler.class).to(DefaultExceptionHandler.class);
bind(SecurityCookieAccessor.class).to(DefaultSecurityCookieAccessor.class);
bind(ClientActionHandlerRegistry.class).to(DefaultClientActionHandlerRegistry.class);
bind(DispatchAsync.class).toProvider(DispatchAsyncProvider.class).in(Singleton.class);
}
public static class DispatchAsyncProvider implements Provider<DispatchAsync> {
private final DispatchAsync fDispatchAsync;
@Inject
public DispatchAsyncProvider(ExceptionHandler eh, SecurityCookieAccessor sca, ClientActionHandlerRegistry cahr) {
this.fDispatchAsync = new RpcDispatchAsync(eh, sca, cahr);
}
@Override
public DispatchAsync get() {
return fDispatchAsync;
}
}
}
MyClientInjector.java - инжектор обеспечивает доступ к DispatchAsync
import com.google.gwt.inject.client.GinModules;
import com.google.gwt.inject.client.Ginjector;
import com.gwtplatform.dispatch.shared.DispatchAsync;
@GinModules(MyClientModule.class)
public interface MyClientInjector extends Ginjector {
DispatchAsync getDispatchAsync();
}
Сервер:
MyGuiceServletContextListener.java - создать инжектор для сервлета, который принимает команды и servermodule, в котором привязки между (clientide) командой и (serveride) обработчиком определены Нед.
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
public class MyGuiceServletContextListener extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new ServerModule(), new DispatchServletModule());
}
}
DispatchServletModule.java - настраивает сервлет, который принимает команды
import com.google.inject.servlet.ServletModule;
import com.gwtplatform.dispatch.server.guice.DispatchServiceImpl;
import com.gwtplatform.dispatch.server.guice.HttpSessionSecurityCookieFilter;
import com.gwtplatform.dispatch.shared.Action;
import com.gwtplatform.dispatch.shared.SecurityCookie;
public class DispatchServletModule extends ServletModule {
@Override
public void configureServlets() {
bindConstant().annotatedWith(SecurityCookie.class).to("JSESSIONID");
filter("*").through(HttpSessionSecurityCookieFilter.class);
serve("/" + Action.DEFAULT_SERVICE_NAME + "*").with(DispatchServiceImpl.class);
}
}
ServerModule.Java - привязки между командой() и клиентской() обработчиком на стороне сервера
import com.gwtplatform.dispatch.server.guice.HandlerModule;
public class ServerModule extends HandlerModule {
@Override
protected void configureHandlers() {
bindHandler(YourCommand.class, YourHandler.class);
}
}
web.xml - рассказать веб-сервер для использования MyGuiceServletContextListener
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--
This Guice listener hijacks all further filters and servlets. Extra
filters and servlets have to be configured in your
ServletModule#configureServlets() by calling
serve(String).with(Class<? extends HttpServlet>) and
filter(String).through(Class<? extends Filter)
-->
<listener>
<listener-class>de.gwtpdispatch.server.MyGuiceServletContextListener</listener-class>
</listener>
Использования
сейчас вы можете создать инжектор с отложенным привязкой и получить доступ к экземпляру DispatchAsync:
MyClientInjector injector = GWT.create(MyClientInjector.class);
injector.getDispatchAsync().execute(...YourCommand...)
(И: Не забудьте включить банки джина и Guice в вашем проекте и добавить джин-модуль gwt.xml проекта)
Я надеюсь, что это объяснение достаточно детализировано. Счастливое кодирование :)
Спасибо! Я сам это понял (как вы отметили, решение стало ясным, как только я понял, что мне нужно использовать DI). Я собираюсь принять ваш ответ, хотя, потому что это правильно, и я ценю, что вы тратите время! – user1452076