1.使用类中的静态方法直接访问
//获取request对象.
HttpServletRequest request = ServletActionContext.getRequest();
//获取session对象.
Map session = ActionContext.getContext().getSession();
//获取application对象.
ServletContext application = ServletActionContext.getServletContext();
这种方法虽然直观简单,但是不便于单元测试。
2.
ActionContext context=ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest)context.get(ServletActionContext.HTTP_REQUEST);
3..实现相应的接口Aware,然后由Struts2的工厂注入对象。
public class HelloStruts extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
在action中,可以将多个属性封装到一个类里,再创建一个类的实例化对象,将类的对象存到session中,在登录或显示结果页面用user.username,user.password显示,或#session.user.username.