在struts中有两种方式可以得到这些对象
非IoC方式
要获得上述对象关键Struts 中comopensymphonyxworkActionContext类我们可以通过它的静态方法getContext()获取当前Action的上下文对象有了这个对象我们想获得其他几个对象就好办了
ActionContext ctx = ActionContextgetContext();
Map session = ctxgetSession();
细心的朋友可以发现这里的session是个map对象在Struts中底层的session都被封装成了Map类型我们可以直接操作这个map 进行对session的写入和读取操作而不用去直接操作HttpSession对象
另外orgapachestrutsServletActionContext作为辅助类(Helper Class)可以帮助您快捷地获得这几个对象
HttpServletRequest request = ServletActionContextgetRequest();
HttpServletResponse response = ServletActionContextgetResponse();
HttpSession session = requestgetSession();
如果你只是想访问session的属性(Attribute)你也可以通过ActionContextgetContext()getSession()获取或添加session范围(Scoped)的对象
IoC方式(这种方式在tapestry中也是这样实现的)
要使用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) {
thisatt = att;
}
publicvoid setServletRequest(HttpServletRequest request) {
thisrequest = request;
}
publicvoid setServletResponse(HttpServletResponse response) {
thisresponse = response;
}
@Override
public String execute() {
attput(msg Hello World from Session!);
HttpSession session = requestgetSession();
StringBuffer sb =new StringBuffer(Message from request: );
sbappend(requestgetParameter(msg));
sbappend(
Response Buffer Size: );
sbappend(responsegetBufferSize());
sbappend(
Session ID: );
sbappend(sessiongetId());
message = sbtoString();
return SUCCESS;
}
}
在strutsxml的action中配置拦截器
<interceptorref name=servletConfig></interceptorref>