Ringo和Spring集成

Ringo with Spring

可以设想,集成了Spring之后,RingoJS就不收任何限制了,JavaScript语言的灵活性,加上Java & Spring 的完善功能,感觉上就应该可以做出很帅的东西……

>>

因为觉得在集成使用Ringo和Spring方面有很多值得一说,Jim Cook就Share了部分他们使用的代码,这部分代码可以让我们更加容易的在Ringo中引用ApplicationContext。下文的例子即基于Jim Cook分享的代码。

Ringo 使用org.ringojs.jsgi.JsgiServlet来bootstrapSSJS环境,我们可以扩展这个类,以提供一些Spring helper函数,帮助我们在Ringo中访问Spring。

package org.ringojs.jsgi;

 

import org.springframework.context.ApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

 

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

 

publicclass ExtJsgiServlet extends JsgiServlet {

 

private ApplicationContext _springContext;

 

@Override

public void init(ServletConfig config)throws ServletException {

super.init(config);

final ServletContext context = config.getServletContext();

_springContext = WebApplicationContextUtils

.getRequiredWebApplicationContext(context);

}

 

public ApplicationContext getSpringContext(){

return _springContext;

}

 

public Object getBean(String name){

return _springContext.getBean(name);

}

}

 

修改web.xml

<servlet>

<servlet-name>ringo</servlet-name>

<servlet-class>org.ringojs.jsgi.ExtJsgiServlet</servlet-class>

<init-param>

<param-name>optlevel</param-name>

<param-value>0</param-value>

</init-param>

</servlet>

 

<servlet-mapping>

<servlet-name>ringo</servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>

 

非常方便,现在我们我们可以通过request.env属性来访问Servlet(ExtJsgiServlet),env属性是JSGI规范的一部分。Ringo中使用spring的代码示例:

app.post('/profiles/:profileId',function(req, profileId){

// Get access to the servlet using the 'env' garbage dump property.

var servlet = req.env.servlet;

 

// Use the servlet's getBean(String) function to

// retrieve a configured bean from Spring.

var datasource = servlet.getBean('datasource');

 

// Or maybe you are using Spring's reloadable resource bundles for

// externalizing your website's localized content.

var context = servlet.getSpringContext();

var welcomeMessage = context

.getMessage('welcome',null, req.env.servletRequest.locale);

});

Leave Comment