Vikings

调用jsonrpc的技巧

一段不用每个jsp页面都JSONRPCBridge.registerObject的方法

1. JsonContextLinster
在spring文件里读取需要注册bridge的bean名单
registerObject
public class JSONContextListener implements ServletContextAttributeListener {
    
private final Log log = LogFactory.getLog(JSONContextListener.class);

    
public void attributeAdded(ServletContextAttributeEvent event) {
        
if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
            
// register LookupHelper so we can call methods on it
            ApplicationContext ctx = (ApplicationContext) event.getValue();

            
// check for null so we don't have to initialize Spring in tests
            if (ctx != null{
                log.debug(
"Registering jsonObjects for XmlHttpRequest to GlobalBridge");
                
                JSONRPCBridge jsonBridge 
= JSONRPCBridge.getGlobalBridge();

                Map jsonObjects 
= (Map) ctx.getBean("jsonObjects");
                
for (Object name : jsonObjects.keySet()) {
                    jsonBridge.registerObject(name, jsonObjects.get(name));
                }

                
            }

        }
        
    }

public void attributeReplaced(ServletContextAttributeEvent event) {
        attributeAdded(event);
    }

}


2.spring配置里的jsonObject
    <!-- json registration -->
    
<bean name="jsonObjects" class="java.util.HashMap">
        
<constructor-arg>
            
<map>
                
<entry key="information" value-ref="informationJson"></entry>
            
</map>
        
</constructor-arg>
    
</bean> 

    
<bean id="informationJson" class="com.vikings.tools.json.Information" >
        
<property name="informationDAO" ref="informationDAO" />
    
</bean>

3.web.xml里增加配置刚才写的listener
<listener>
        
<listener-class>com.vikings.tools.json.JSONContextListener</listener-class>
    
</listener>

到这里就不用这么写了
<jsp:useBean id="JSONRPCBridge" scope="session"
   class
="com.metaparadigm.jsonrpc.JSONRPCBridge" />

<% JSONRPCBridge.registerObject("myTestObject", aTestObject); %>
这个也不需要
// Find the JSONRPCBridge for this session or create one
// if it doesn't exist. Note the bridge must be named "JSONRPCBridge"
// in the HttpSession for the JSONRPCServlet to find it.
HttpSession session = request.getSession();
JSONRPCBridge json_bridge 
= null;
json_bridge 
= (JSONRPCBridge) session.getAttribute("JSONRPCBridge");
if(json_bridge == null{
    json_bridge 
= new JSONRPCBridge();
    session.setAttribute(
"JSONRPCBridge", json_bridge);
}

posted on 2007-11-01 22:19 Vikings 阅读(1467) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: