spring和gwt整合,让gwt直接调用spring bean的前端servlet(一)

2014-11-24 08:29:22 · 作者: · 浏览: 7
gwt和spring整合的关键是让gwt可以访问到spring的bean,先在提供一个前端servlet分发器,配置了这个servlet后,gwt的RemoteServiceServlet就不用在web.xml中一个一个的配置了。本文使用的gwt是2.5.1版本的,spring是3.2.4版本的。
1、服务层接口:要在client包或者子包下面,@RemoteServiceRelativePath标识这个servlet的相对路径,里面的值是spring bean的id
[java]
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* The client side stub for the RPC service.
*/
@RemoteServiceRelativePath("greetingServiceImpl")
public interface GreetingService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
}
2、服务层异步接口,就是服务接口后加Async,和服务层接口在同一个包下面
[java]
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* The async counterpart of GreetingService.
*/
public interface GreetingServiceAsync {
void greetServer(String input, AsyncCallback callback)
throws IllegalArgumentException;
}
3、这个是gwt和spring整合的前端servlet总控制器,在inti方法中,设置该类可以自动装配。
[java]
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class SpringGwtRemoteServiceServlet extends RemoteServiceServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(SpringGwtRemoteServiceServlet.class);
public void init() throws ServletException {
super.init();
if (LOG.isDebugEnabled()) {
LOG.debug("Spring GWT service exporter deployed");
}
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
factory.autowireBean(this);
}
public String processCall(String payload) throws SerializationException {
try {
Object handler = getBean(getThreadLocalRequest());
RPCRequest rpcRequest = RPC.decodeRequest(payload, handler.getClass(), this);
onAfterRequestDeserialized(rpcRequest);
if (LOG.isDebugEnabled()) {
LOG.debug("Invoking " + handler.getClass().getName() + "." + rpcRequest.getMethod().getName());
}
return RPC.invokeAndEncodeResponse(handler, rpcRequest.getMethod(),
rpcRequest.getParameters(),
rpcRequest.getSerializationPolicy());
} catch (IncompatibleRemoteServiceException ex) {
log