處理方式:
介面主方
(1)在web.xml中配置相應的servlet 用以處理所有的請求
<servlet>
<servlet-name>hessianServerServlet</servlet-name>
<servlet-class>com.psychcn.cmi3.web.servlet.HessianServerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hessianServerServlet</servlet-name>
<url-pattern>/hessian/*</url-pattern>
</servlet-mapping>
編寫servlet
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.remoting.caucho.HessianServiceExporter;
import org.springframework.web.util.UrlPathHelper;
import com.psychcn.util.SpringUtils;
public class HessianServerServlet extends HttpServlet {
private static final long serialVersionUID = -7579598882061647014L;
ConcurrentMap<String, HessianServiceExporter> hessianExporterMappings =
new ConcurrentHashMap<String, HessianServiceExporter>();
UrlPathHelper urlPathHelper = new UrlPathHelper();
private ApplicationContext ac = null;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String requestPath = urlPathHelper.getPathWithinServletMapping(request);
if (requestPath!= null && requestPath.length() > 1) {
HessianServiceExporter exporter = hessianExporterMappings.get(requestPath);
if (exporter != null) {
exporter.handleRequest(request, response);
} else {
response.setCharacterEncoding("utf-8");
response.getWriter().println("未找到相應的服務,請檢查 Hessian URL 是否正確 (error url: " + requestPath + ")");
}
} else {
response.setCharacterEncoding("utf-8");
response.getWriter().println("請求的是根路徑,請檢查 Hessian URL 是否配置正確");
}
}
@Override
public void init(ServletConfig config) throws ServletException {
this.ac = SpringUtils.getWebApplicationContext(config.getServletContext());
if (this.ac != null) {
// 將Spring容器中定義的 HessianServiceExporter 均緩衝到本執行個體變數中
this.hessianExporterMappings.putAll(ac.getBeansOfType(HessianServiceExporter.class));
} else {
super.log("錯誤,Hessian 服務元件無法擷取 Spring 上下文");
}
}
@Override
public void destroy() {
ac = null;
hessianExporterMappings.clear();
super.destroy();
}}
spring xml中的配置
<bean id="cmiService" class="com.psychcn.cmi3.remoting.hessian.CmiServiceHessianImpl" >
<constructor-arg index="0" ref="mainDataSource" />
</bean>
<bean name="/cmiService" class="org.springframework.remoting.caucho.HessianServiceExporter">
<property name="service" ref="cmiService" />
<property name="serviceInterface" value="com.psychcn.cmi3.remoting.CmiService" />
</bean>
編寫相應的介面即實作類別:
public interface CmiService {}
public class CmiServiceHessianImpl extends ServiceImpl implements CmiService, InitializingBean, ApplicationContextAware {}