在Struts2中怎样用Groovy语言来写Action

我们在作Struts2的项目时,如果我们更新了Java程序(这里主要是指Action)我们需要重新启动Tomcat或者Web Context。这样的开发有时确实比较影响工作效率,每天都有很多时间好消耗到这个上面,工作之余想了一个办法,就是使用Groovy来作为 Struts2的Action。
这里我使用Struts2+Spring+Groovy1.0来做一个列子。
  • 首先需要添加Groovy的jar包,主要包括groovy, asm 和antlr 包,具体信息可以查看spring2.0-reference.pdf.
  • 假定已经配置好了struts2+srping的开发环境。
  • 使用Groovy语言来写一个Action,如下(GroovyHelloWorldAction.groovy)
    import com.opensymphony.xwork2.ActionSupport;

    class GroovyHelloWorldAction extends ActionSupport {

        
    static final String MESSAGE = "This is Groovy Hello World!";

        String message ;
        
        
    public String execute() throws Exception {
            message 
    = MESSAGE;
            
    return SUCCESS;
        }
        
    }
  • 在spring的配置文件中指定此Groovy Action bean, 如下
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi
    ="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop
    ="http://www.springframework.org/schema/aop"
           xmlns:lang
    ="http://www.springframework.org/schema/lang"
           xsi:schemaLocation
    ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
                               http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd"

           default-lazy-init
    ="true">

        
    <lang:groovy id="groovyHelloWorldAction" 
            script-source
    ="classpath:GroovyHelloWorldAction.groovy"
            scope="prototype"
    >
            
        
    </lang:groovy>
    </beans>
注意其中对schema的引用。
  • 在Strugs的配置文件中添加配置
    <action name="groovyHelloWorld" class="groovyHelloWorldAction">
            
<result>/helloworld.jsp</result>
        
</action>
  • 添加一个helloworld.jsp页面,内容如下:
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
    
<head>
        
<title>Groovy Hello World!</title>
    
</head>
    
<body>
        
<h2><s:property value="message" /></h2>
    
</body>
</html>
  • 测试
启动Tomcat,在访问http://localhost:8080/myapp/groovyHelloWorld.action
 
posted @ 2007-07-23 22:28  程序员天下  阅读(127)  评论(0编辑  收藏  举报