一.前言
Action中的方法代表业务逻辑,那么一个模块中的多个业务逻辑如何用Action来处理呢?我们有2种办法来处理这个问题:
1.一个Action对应一个业务逻辑,实现方便,但是Action数量多,struts.xml中需要配置的内容也多,这种方法不推荐;
2.一个Action对应多个业务逻辑,例如表的一些操作,含有多个业务逻辑,我们只写一个Action来实现,Action的数量没有增加,struts.xml的配置也简单,所以这种方法是我们推荐的做法。
二.例子
以下是MyAction类的四个方法
public class MyAction extends ActionSupport implements ModelDriven<User> {
// crud业务方法
private UserService userservice = new UserService();
private User user=new User();
// 模型对象userinfo
public User getModel() {
// TODO Auto-generated method stub
return user;
}
// 增加
public String create() throws Exception {
userservice.createUser(user);
return SUCCESS;
}
// 查询
public String retrive() throws Exception {
// 查询结果放在request中
ActionContext.getContext().put("userlist", userservice.selectUsers());
return "list";
}
// 修改
public String update() throws Exception {
userservice.updateUser(user);
return SUCCESS;
}
// 删除
public String delete() throws Exception {
userservice.deleteUser(user.getId());
return SUCCESS;
}
}
struts.xml文件配置<struts>
<package name="actions" namespace="/" extends="struts-default">
<action name="MyAction_*" class="com.eduask.chp.action.MyAction" method="{1}">
<result>success.jsp</result>
<result name="list">UserList.jsp</result>
<allowed-methods>update,create,retrive,delete</allowed-methods>
</action>
</package>
</struts>
<body>
<a href="MyAction_update" >修改用户</a>
<a href="MyAction_create">新增用户</a>
<a href="MyAction_retrive">查询用户</a>
<a href="MyAction_delete">删除用户</a>
</body>