在Struts2.0中,Action已经与Servlet API完全分离,这使得Struts2.0的Action具有了更加灵活和低耦合的特性,与Struts1.0相比较而言是个巨大的进步。但是如果在Action访问Servlet API,可以使用一下方法:
使用com.opensymphony.xwork2.ActionContext类。该类提供了以下方法:
Object get(Object key) :通过参数key来查找当前ActionContext中的值
Map getApplication() :返回一个Application级的Map对象
Static ActionContext getContext() :获得当前线程的ActionContext对象
Map getParameters() :返回一个包含所有HttpServletRequest参数信息的Map对象
Map getSession() :返回一个Map类型的HttpSession对象
Void put(Object key,Object value) :向当前ActionContext对象中存入名值对信息
Void setApplication(Map application) :设置Application上下文
Void setSession(Map session) :设置一个Map类型的Session值
通过这些方法可以方便的访问到几个Servlet API对象,注意这些对象为Map类型。
另外,可以直接使用org.apache.struts2.ServletActionContext类访问这些API:
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。具体实现:
publicclass IoCServlet extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {
private String message;
private Map att;
private HttpServletRequest request;
private HttpServletResponse response;
public String getMessage() {
return message;
}
publicvoid setSession(Map att) {
this.att = att;
}
publicvoid setServletRequest(HttpServletRequest request) {
this.request = request;
}
publicvoid setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public String execute() {
att.put("msg", "Hello World from Session!");
HttpSession session = request.getSession();
StringBuffer sb =new StringBuffer("Message from request: ");
sb.append(request.getParameter("msg"));
sb.append("
Response Buffer Size: ");
sb.append(response.getBufferSize());
sb.append("
Session ID: ");
sb.append(session.getId());
message = sb.toString();
return SUCCESS;
}
}
在struts.xml的action中配置拦截器
<interceptor-ref name="servletConfig"></interceptor-ref>