在Struts2访问 HttpServletRequest、HttpSession、ServletContext三个域对象

时间:2022-01-01 13:03:45
Struts2如何访问 HttpServletRequest、HttpSession、ServletContext三个域对象

1,方法一:与Servlet API解耦的访问方式
通过 ActionContext 访问域对象对应的 Map 对象

public class MyAction extends ActionSupport implements Serializable {
//向各大域范围存放点数据
@Override
public String execute() throws Exception {

ActionContext ac = ActionContext.getContext();

Map<String,Object> applicationMap = ac.getApplication();//这个就是ServletContext对象中维护的那个Map
applicationMap.put("p", "application_p");// 相当于ServletContext.setAttribute(key,object);

Map<String,Object> sessionMap = ac.getSession();//这个就是HttpSession对象中维护的那个Map
sessionMap.put("p", "session_p");// 相当于HttpSession.setAttribute(key,object);

ac.put("p", "request_p");//相当于ServletRequest.setAttribute(key,obj);
return super.execute();
}
}

2,方法二:Servlet API耦合的访问方式
通过 ServletActionContext 直接获取 Servlet API 对象
ServletContext servletContext = ServletActionContext.getServletContext();
ServletRequest servletRequest = ServletActionContext.getRequest();
HttpServletRequest httpServletRequest = (HttpServletRequest)ServletActionContext.getRequest();
HttpSession session = httpServletRequest.getSession();

通过实现 ServletXxxAware 接口的方式使 Struts2 注入对应的对象

public class MyAction extends ActionSupport implements Serializable,ServletContextAware,ServletRequestAware,ServletResponseAware,SessionAware {

private ServletContext context;
private HttpServletRequest request;
private HttpServletResponse response;
private Map sessionMap;

// 如果Action类实现了ServletContextAware接口,就会自动调用该方法
public void setServletContext(ServletContext context) {
this.context = context;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setSession(Map<String, Object> session) {
this.sessionMap = session;
}

public String execute(){
System.out.println(context);
System.out.println(request);
System.out.println(response);
System.out.println(sessionMap);
return SUCCESS;
}
}