gwt(google web toolkit) 和 spring 在一起使用列子
在开发gwt时,有时需要同spring进行结合使用
?
下面是我根据spring4gwt上给出的相关信息做出来的一个demo
?
1、使用maven对jar包进行管理
?
2、自己写一个继承于RemoteServiceServlet的java文件
?
下面就将spring和gwt结合起来的代码:
主要思想就是
1、将请求解析为spring支持的bean
2、获取请求的方法和参数
3、调用方法和参数,并将结果返回
?
}// 使用反射方式调用实例对象的方法, 返回调用结果
return RPC.invokeAndEncodeResponse(handler, rpcRequest.getMethod(), rpcRequest.getParameters(), rpcRequest
.getSerializationPolicy());
} catch (IncompatibleRemoteServiceException ex) {
log("An IncompatibleRemoteServiceException was thrown while processing this call.", ex);
return RPC.encodeResponseForFailure(null, ex);
}
}
/**
* 基于request URL进行的获取实例bean的操作
* 比如说:请求结尾时/myService,那么我们就会将spring中的bean实例为myService
*
* @param request
* @return handler bean
*/
protected Object getBean(HttpServletRequest request) {
String service = getService(request);
// 从spring中的applicationContext中取出bean
Object bean = getBean(service);
if (!(bean instanceof RemoteService)) {
throw new IllegalArgumentException("Spring bean is not a GWT RemoteService: " + service + " (" + bean + ")");
}
if (LOG.isDebugEnabled()) {
LOG.debug("Bean for service " + service + " is " + bean);
}
return bean;
}
/**
* 解析bean的名称,通过request来解析
* 如/spring 会被解析为 spring
* @param request
* @return bean name
*/
protected String getService(HttpServletRequest request) {
// 获得url
String url = request.getRequestURI();
// 对取最后一个"/"后面的内容
String service = url.substring(url.lastIndexOf("/") + 1);
if (LOG.isDebugEnabled()) {
LOG.debug("Service for URL " + url + " is " + service);
}
return service;
}
/**
* 在当前webApplicationContext中取出bean的实例
*
* @param name
* bean name
* @return the bean
*/
protected Object getBean(String name) {
// 调用spring自带的utils
WebApplicationContext applicationContext = WebApplicationContextUtils
.getWebApplicationContext(getServletContext());
if (applicationContext == null) {
throw new IllegalStateException("No Spring web application context found");
}
if (!applicationContext.containsBean(name)) {
{
throw new IllegalArgumentException("Spring bean not found: " + name);
}
}
// 获取bean实例
return applicationContext.getBean(name);
}
}