Struts2-第三篇-CodeingStruts2Action

本文介绍了如何使用Struts2框架创建Action,包括映射Action到类、映射结果到视图,以及如何处理表单输入。通过示例展示了如何设置和获取表单字段值,并在Action中更新状态。

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

编写一个Struts2 Action时,涉及几个部分:

1、Mapping一个action到一个类。

2、Mapping一个result到一个view

3、在Action类中编写控制逻辑


Action Mapping: 

<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">
    <result name="success">/HelloWorld.jsp</result>
</action>
上面Action mapping指定如果执行HelloWorldAction类的方法,返回success时,然后到视图HelloWorld.jsp并返回到浏览器

Struts2 Action Classes

Action类在MVC开发模式中,扮演着控制器的作用。Action类响应一个用户action,执行业务逻辑,然后返回一个result并告诉Struts显示什么。

Struts2 Action类通常继承ActionSupport类,它是由Struts2 Framework框架提供。类ActionSupport提供缺省继承大部分的公共actions,并且也实现一些有用的Struts2接口。当你的Action类继承ActionSupport,你能重写缺省的继承或者是继承他们。

Processing Form Input In the Action Class

Action类的众多功能职责之一是去处理输入方式,然后使处理的result对应到view 页面。

在index.jsp中添加如下代码:

<s:form action="hello">
 
    <s:textfield name="userName" label="Your name" />
     
    <s:submit value="Submit" />
 
</s:form>
Make a note of the value of the name attribute for the Struts 2 textfield tag, which is userName. When the user clicks on the submit button for the above form, the action hello will be executed (hello.action). The form field values will be posted to the Struts 2 Action class (HelloWorldAction). The Action class may automatically receive those form field values provided it has a public set method that matches the form field name value.

在类HelloWorldAction中,添加如下代码:

private String userName;
 
public String getUserName() {
    return userName;
}
 
public void setUserName(String userName) {
    this.userName = userName;
}

对于个人的MessageStore message添加如下java代码到HelloWorldAction's execute方法,Add userName value to message

if (userName != null) {
             
    messageStore.setMessage( messageStore.getMessage() + " " + userName);
             
}

部署项目:http://localhost:8080/Coding_Struts2_Actions/index.action


当点击Submit时,struts将调用HelloWorldAction类中匹配的格式输入名字的任何方法。因此在这个例子方法中,setUserName被调用并且通过用户输入的值在UserName field。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值