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

本文介绍如何使用Groovy语言编写Struts2的Action,通过配置Groovy的jar包并利用Spring进行bean定义,实现了无需重启服务器即可更新业务逻辑的目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在作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)
    importcom.opensymphony.xwork2.ActionSupport;

    classGroovyHelloWorldActionextendsActionSupport...{

    staticfinalStringMESSAGE="ThisisGroovyHelloWorld!";

    Stringmessage;

    publicStringexecute()throwsException...{
    message
    =MESSAGE;
    returnSUCCESS;
    }

    }
  • 在spring的配置文件中指定此Groovy Action bean, 如下
    <?xmlversion="1.0"encoding="UTF-8"?>
    <beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/langhttp://www.springframework.org/schema/lang/spring-lang-2.0.xsd"

    default-lazy-init
    ="true">

    <lang:groovyid="groovyHelloWorldAction"
    script-source
    ="classpath:GroovyHelloWorldAction.groovy"
    scope="prototype"
    >

    </lang:groovy>
    </beans>
注意其中对schema的引用。
  • 在Strugs的配置文件中添加配置
<actionname="groovyHelloWorld"class="groovyHelloWorldAction">
<result>/helloworld.jsp</result>
</action>
  • 添加一个helloworld.jsp页面,内容如下:
<%...@taglibprefix="s"uri="/struts-tags"%>
<html>
<head>
<title>GroovyHelloWorld!</title>
</head>
<body>
<h2><s:propertyvalue="message"/></h2>
</body>
</html>
  • 测试
启动Tomcat,在访问http://localhost:8080/myapp/groovyHelloWorld.action
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值