SSH学习--struts的action中BaseAction的作用

来源:互联网 发布:有淘宝店铺可以直播吗 编辑:程序博客网 时间:2024/05/16 06:20

通常struts中的action一般都是继承ActionSupport的

public void loginCheck() throws Exception {HttpServletResponse response = ServletActionContext.getResponse();response.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();try {out.println(userLogic.loginCheck(userDTO.getUserLoginName(), userDTO.getUserPwd()));} catch (Exception e) {e.printStackTrace();} finally {out.flush();out.close();}}

而发现有些项目中的则是继承BaseAction的

public void loginCheck() throws Exception {PrintWriter out = getWriter();try {accountLogic.getAllAccount();out.flush();} catch (Exception e) {e.printStackTrace();} finally {out.close();}}

ActionSupport是struts2自带的类, BaseAction是自己的一个封装
这是BaseAction中的内容:
public class BaseAction extends ActionSupport {private static final long serialVersionUID = 1L;PrintWriter getWriter() throws IOException {HttpServletResponse response = ServletActionContext.getResponse();response.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");return response.getWriter();}HttpSession getSession(){HttpServletRequest request = ServletActionContext.getRequest();return request.getSession();}}

可以看出BaseAction1也是继承自ActionSupport的,只是里面增加一些公用的属性和方法,例如获取httpRequest,又比如获取用户信息的方法,完全是自己封装的。

这样做避免每个action甚至每个方法都要写这些,增加了代码的复用性。

0 0
原创粉丝点击