我今天刚开始学习一些 JSP 和 servlet,想知道是否可以将会话ServletContext
作为变量并将其传递给普通的 Java 类?如果是这样,我该怎么做?
我的简单servlet:
public class myServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
//How do I receive the servlet context below in a plain Java class?
ServletContext sc = session.getServletContext();
request.setAttribute("sc", sc);
}
}
我的 Java 类只是一个普通的类:
public class myClass extends HttpServlet {
//I want to be able to use the ServletContext as a variable that is passed from myServlet class into this one.
}
在myClass
我希望能够使用它来获取我的项目中文件的真实路径文件:
ServletContext sc
String path = sc.getRealPath(...)
编辑: 我可以在myServlet
servlet 中做这样的事情吗?:
String realPath = sc.getRealPath("/WEB-INF/myFile");
但是,如何将这个realPath
变量传递给myClass
我,以便我可以在那里而不是 in 使用它myServlet
?