如何获取ServletContext对象
作者:-- 发布时间:2019-11-20 10:18:39
在struts2中,可以使用以下两种方法来获取servletcontext对象。
1. servletactioncontext
直接从 org.apache.struts2.servletactioncontext 获取 servletcontext 对象。
import javax.servlet.servletcontext;
import org.apache.struts2.servletactioncontext;
import com.opensymphony.xwork2.actionsupport;
public class customeraction extends actionsupport{
public string execute() throws exception {
servletcontext context = servletactioncontext.getservletcontext();
return success;
}
}
2. servletcontextaware
让你的类实现了org.apache.struts2.util.servletcontextaware接口。
当struts2 的 “servlet-config”拦截器是看到了一个action类实现servletcontextawareinterface,它会通过一个servletcontext引用action类通过setservletcontext()方法请求。
import javax.servlet.servletcontext;
import org.apache.struts2.util.servletcontextaware;
import com.opensymphony.xwork2.actionsupport;
public class customeraction
extends actionsupport implements servletcontextaware{
servletcontext context;
public string execute() throws exception {
return success;
}
public void setservletcontext(servletcontext context) {
this.context = context;
}
}
参考
-
struts 2 servletcontextaware文档