下面是网络流行的两种方式,推荐使用IOC这种。
package com.alpha.test; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware { private static final long serialVersionUID = 1L; // not IOC ActionContext context = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE); @SuppressWarnings("unchecked") Map session = context.getSession(); //Map session = (Map) context.get(ActionContext.SESSION); // IOC @SuppressWarnings("unchecked") public void setSession(Map session) { this.session = session; } public void setServletRequest(HttpServletRequest request) { this.request = request; } public void setServletResponse(HttpServletResponse response) { this.response = response; } }
本文介绍了一种在Struts2框架中使用依赖注入(IOC)的方法,并将其与非IOC的方式进行了对比。通过示例代码展示了如何在BaseAction类中实现这两种不同的依赖获取方式。
620

被折叠的 条评论
为什么被折叠?



