将ServletContext接收到纯Java类中?

时间:2018-11-15 04:01:51

标签: java jsp session servlets realpath

我今天才刚开始学习一些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中,以便可以在那里而不是在myServlet中使用它?

1 个答案:

答案 0 :(得分:0)

  1. 创建课程

    public class MyClass {....}

  2. 具有类型ServletContext

    的变量

    private ServletContext myContext;

  3. 通过构造方法或设置方法设置值

    void setContext (ServletContext sc) {myContext = sc;}

  4. 使用

    myContext.get....("xxx");

修改

您可以将servlet中的此类用作

doPost (....) {

   ....
    ServletContext sc = session.getServletContext();
   MyClass mc = new MyClass ();
   mc.setContext (sc);

 // now the context is **in** the MyClass instance - how you use it is up to you.