由于我希望提供各种客户端来连接Spring提供的服务,
(客户端种类至少包括:Flex/AIR、MS WinForm、Ajax、纯JSP)
所以Spring必须识别不同种类的客户端,并从中取得request,这样才能拿到类似IP地址这样的客户端信息。
这里说的“取得”,不是在JSP的代码里,JSP里根本不用“取得”,request就在那里。
这里是说在,Spring的代码中,如何识别各种客户端,并取得request
HttpServletRequest request = null;
if (request == null) {
// JSP客户端
try {
// TODO 如何在纯JSP发送过来请求的时候,得到request?
if (request != null) {
log.info("Connected a Web client with JSP.");
}
} catch (Exception e) {
}
}
if (request == null) {
// Struts2客户端
try {
//request = (HttpServletRequest)ServletActionContext.getRequest();
// 把上一行的代码,变成反射的写法,是为了在不使用Struts2前台的应用中就可以不必需要Struts2的jar包了
Class c;
c = Class.forName("org.apache.struts2.ServletActionContext");
Method m = c.getMethod("getRequest", new Class[] {});
request = (HttpServletRequest) m.invoke(c, new Object[] {});
if (request != null) {
log.info("Connected a Web client with Struts2.");
}
} catch (Exception e) {
}
}
if (request == null) {
// Hessian客户端
try {
//request = (HttpServletRequest)ServiceContext.getContextRequest();
// 把上一行的代码,变成反射的写法,是为了在不使用Hessian做RPC的应用中就可以不必需要Hessian的jar包了
Class c;
c = Class.forName("com.caucho.services.server.ServiceContext");
Method m = c.getMethod("getContextRequest", new Class[] {});
request = (HttpServletRequest) m.invoke(c, new Object[] {});
if (request != null) {
log.info("Connected a .Net client with Hessian RPC.");
}
} catch (Exception e) {
}
}
if (request == null) {
// Flex/AIR客户端
try {
//request = FlexContext.getHttpRequest();
// 把上一行的代码,变成反射的写法,是为了在不使用Flex/AIR前台的应用中就可以不必需要Flex的jar包了
Class c;
c = Class.forName("flex.messaging.FlexContext");
Method m = c.getMethod("getHttpRequest", new Class[] {});
request = (HttpServletRequest) m.invoke(c, new Object[] {});
if (request != null) {
log.info("Connected a Flex/AIR client with AMF RPC.");
}
} catch (Exception e) {
}
}
String ipAddress = "";
if (request != null) {
ipAddress = request.getRemoteAddr();
if ("".equals(ipAddress)) {
log.info("Client IP Address is unknow.");
} else {
log.info("Client IP Address is: " + ipAddress);
}
}
以上代码,在Spring中完成了对 Struts2、Hessian、AMF(BlazeDS)的识别,并提取requst。
但是,目前我还没有找到普通的纯JSP来调用Spring时,该如何取得request的方法。
(JSP中调用Spring的代码如下:)
ServletContext servletContext = request.getSession().getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
MyService myService=(MyService)wac.getBean("myService"); // "myService"是Spring中注入的服务Bean
如知道这个(第一段代码中的TODO部分)怎么写的,请给我个回复,谢谢了。
------------------------六年后的一条分割线---------------------------------
无意中翻出这篇老博文,文章中留下的遗憾“纯JSP如何获取request”早已“破解”
// 要在web.xml增加如下监听器:
// <listener>
//<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
// </listener>
request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
而且,当if/else if太多了以后,这么写真的不太雅观。
因此,我推荐采用“责任链模式”,把这段代码改写一下,具体如何使用责任链模式,已经超出本文的范畴,感兴趣的话,去看一下讲设计模式的文章吧。