Struts2学习笔记(二):Action 的三种开发模式

本文介绍了Struts框架中Action的三种开发模式:继承ActionSupport类、实现Action接口及不继承也不实现接口的方式,并展示了如何在struts.xml中配置这些Action。

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

项目结构:

 

UserAction.java: 

/**
 * Action 的开发模式1:继承 ActionSupport 类;
 *  如果使用 struts 的数据校验功能,必须继承 ActionSupport;
 */
public class UserAction extends ActionSupport {
    /**
     * Action 中业务处理方法
     */
    public String login(){
        System.out.println("login");
        return "login";
    }
}

UserAction2.java: 

/**
 * Action 的开发模式2:实现 Action 接口;
 */
public class UserAction2 implements Action {
    /**
     * Action 中业务处理方法
     */
    public String login(){
        System.out.println("login");
        return "login";
    }

    @Override
    public String execute() throws Exception {
        return "success";
    }
}

UserAction3.java: 

/**
 * Action 的开发模式3:既不实现 Action 接口,也不加成 ActionSupport 类;
 */
public class UserAction3 {
    /**
     * Action 中业务处理方法
     */
    public String login(){
        System.out.println("login");
        return "login";
    }
}

为了避免 struts.xml 中配置内容过多,可以把 struts 的配置拆分,每个业务模块中定义一个 配置文件,用 struts.xml 引入:

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
	"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<!-- struts 在运行的时候会加载这个总配置文件:src/struts.xml -->

	<!-- 总配置文件中引入其他所有的配置文件 -->
	<include file="com/struts/demo/user.xml"/>
</struts>

user.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
	"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="user" extends="struts-default">
		<action name="login" class="com.struts.demo.UserAction3" method="login">
			<result name="login">/index.jsp</result>
		</action>
    </package>
</struts>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值