通常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中的内容:
可以看出BaseAction1也是继承自ActionSupport的,只是里面 增加一些公用的属性和方法,例如获取httpRequest,又比如获取用户信息的方法,完全是自己封装的。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(); } }
这样做避免每个action甚至每个方法都要写这些,增加了代码的复用性。