代码结构图以下: web
客户端经过Spring的HttpInvoker,完成对远程函数的调用。涉及的类有:
客户端调用User类的服务UserService,完成对实现类UserServiceImpl的addUser(User u)方法调用。其中User类为普通Pojo对象,UserService为接口,UserServiceImpl为UserService的具体实现。代码以下:
public interface UserService {
void addUser(User u);
} spring
public class UserServiceImpl implements UserService {
public void addUser(User u) {
System.out.println("add user ["+u.getUsername()+ "] ok !!!");
}
} app
客户端调用时,主方法代码为:
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"ApplicationContext.xml" });
UserService us = (UserService)ctx.getBean("ServletProxy");
us.addUser(new User("Hook1"));
UserService us2 = (UserService)ctx.getBean("UrlPathProxy");
us2.addUser(new User("Hook2"));
} 函数
其调用流程用时序图可表示为:
图中粉红色表示基于Url映射方式的配置时程序的处理流程,红色表示基于Servlet配置时的处理流程。
当以示基于Url映射方式的配置时,远程系统处理请求的方式同SpringMVC的controller相似,全部的请求经过在web.xml中的org.springframework.web.servlet.DispatcherServlet统一处理,根据url映射,去对应的【servlet名称-servlet.xml】文件中,查询跟请求的url匹配的bean配置;而基于Servlet配置时,由org.springframework.web.context.support.HttpRequestHandlerServlet去拦截url-pattern匹配的请求,若是匹配成功,去ApplicationContext中查找name与servlet-name一致的bean,完成远程方法调用。 url
当使用URL映射配置时,实力配置以下(application-servlet.xml):
<bean name="/userHttpInvokerService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="userService"/>
<property name="serviceInterface" value="com.handou.httpinvoker.service.UserService"/>
</bean> spa
web.xml文件配置:
<servlet>
<servlet-name>application</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping> 3d
若是使用基于Servlet的配置,web.xml文件配置以下:
<!-- 基于servlet配置时使用 ,根据请求的url匹配url-pattern,若是匹配成功,去ApplicationContext
中查找name与servlet-name一致的bean-->
<servlet>
<servlet-name>userHttpInvokerService</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userHttpInvokerService</servlet-name>
<url-pattern>/UserHttpInvokerService</url-pattern>
</servlet-mapping> xml
applicationContext.xml文件中配置以下:
<bean id="userService" class="com.handou.httpinvoker.service.UserServiceImpl" />
<!--第二种配置方式 -->
<bean name="userHttpInvokerService"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="userService"/>
<property name="serviceInterface" value="com.handou.httpinvoker.service.UserService"/>
</bean> 对象
两种方式,客户端配置均相同:
<bean id="ServletProxy"
class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl">
<value>http://localhost:8080/HttpInvoke/UserHttpInvokerService</value>
</property>
<property name="serviceInterface">
<value>com.handou.httpinvoker.service.UserService</value>
</property>
</bean> 接口
具体可参考源码 :点击下载