将Struts应用迁移到Struts 2(二)(二)

2014-11-24 01:36:55 · 作者: · 浏览: 1
ice.findById( Integer.parseInt(blogForm.getId()));

BeanUtils.copyProperties( blog, blogForm );

service.update( blog );

request.setAttribute("blog",blog);

return (mapping.findForward("success"));

}

}

这三个action都跟随着同一个模式:

产生一个新的业务逻辑对象实例- 如前面所提到的,我们使用最直接的方式在action中使用业务逻辑对象,这表示在每个action中都会产生新的业务逻辑对象实例。

从请求中获得数据- 这是两种形式之一。在view action中,"id"是从HttpServletRequest 对象中直接获取的。而在create 和update action 中,则从ActionForm 中取值。ActionForm 与HttpServletRequest 的调用方式其实很相似,唯一不同的ActionForm 是bean的从field中取值。

调用业务逻辑- 现在开始生成调用业务逻辑所需的参数并调用逻辑。如果参数(在view action中)是一个简单对象类型,则转换值时会自动转为正确的类型(如从String转到Integer)。如果参数是复杂的对象类型,,则ActionForm 需要通过BeanUtil 来帮忙转成相应的对象。

设定返回的数据- 如果需要把数据返回显示给用户,那则要把这个数据设在HttpServletRequest 的attribute 中返回。返回一个ActionForward - 所有Struts action的最后都需要找到并返回其相应的ActionForward 对象.

最后的两个action,remove和list action, 只有很少的差别。remove action如下所示,没有用BlogForm类. 通过从request的attribute中获取"id"(和view action相似),就能调用业务逻辑完成其需要的工作。在下面我们介绍配置时,你可以看到它并没有返回任何数据,因为它的"success"返回结果其实是执行remove后再执行了list action来返回信息的。

public class RemoveBlogEntryAction extends Action ...{

public ActionForward execute(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception ...{

BlogService service = new BlogService();

String id = request.getParameter("id");

service.delete(Integer.parseInt(id));

return (mapping.findForward("success"));

}

}

list action并不需要任何的用户输入,它只是简单地调用了业务逻辑的无参方法,同时返回所有的Blog对象。

public class ListBlogsAction extends Action ...{

public ActionForward execute(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws Exception ...{

BlogService service = new BlogService();

request.setAttribute("bloglist",service.list());

return (mapping.findForward("success"));

}

}