gwt+spring整合
?
目的:让gwt与spring整合
思路:建立一个实现了RemoteServiceServlet的servlet,根据传递的参数调用spring?WebApplicationContext容器里注册的服务,返回结果!
?
实现:
1.建立一个实现了RemoteServiceServlet的servlet
?
public class GwtSpring extends RemoteServiceServlet{ /** * spring容器上下文 */ private WebApplicationContext springContext; /** * 覆盖servlet.init方法 * 获取spring WebApplicationContext容器上下文 */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); springContext = (WebApplicationContext) config.getServletContext().getAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (springContext == null) { throw new RuntimeException("Check Your Web.Xml Setting, No Spring Context Configured"); } } /** * 覆盖RemoteServiceServlet方法 * 获取调用参数,取得容器里的服务对象进行处理,返回处理结果 */ @Override public String processCall(String payload) throws SerializationException { //获取HttpServletRequest对象 HttpServletRequest req = getThreadLocalRequest(); //获取服务对象,此处采用url比对,与servlet url-pattern配合 //url样式:/gwtcrud/spring/* //*号代表容器里服务对象ID String requestURI = req.getRequestURI(); String beanname = requestURI.substring(requestURI.lastIndexOf("/")+1); RemoteService service = (RemoteService) springContext.getBean(beanname); //调用服务对象,返回结果,参考:RemoteServiceServlet.processCall try { RPCRequest rpcRequest = RPC.decodeRequest(payload, service.getClass(), this); return RPC.invokeAndEncodeResponse(service, rpcRequest.getMethod(), rpcRequest.getParameters(), rpcRequest .getSerializationPolicy()); } catch (IncompatibleRemoteServiceException ex) { getServletContext() .log("An IncompatibleRemoteServiceException was thrown while processing this call.",ex); return RPC.encodeResponseForFailure(null, ex); } } }
?
?
2.配置web.xml
?
<servlet> <servlet-name>GwtSpring</servlet-name> <servlet-class>com.gwtcrud.server.GwtSpring</servlet-class> </servlet> <servlet-mapping> <servlet-name>GwtSpring</servlet-name> <url-pattern>/gwtcrud/spring/*</url-pattern> </servlet-mapping>?
?
3.写远程接口
?
/** * 调用spring容器中id为carService的对象 * @author Administrator * */ @RemoteServiceRelativePath("spring/carService") public interface CarService extends RemoteService{ public Car getCar(); public Car saveCar(Car car); public List<Car> getAllCars(); }?
?