为什么ServletContext值对于同一项目的内部和外部调用是不同的?

时间:2014-12-27 22:37:08

标签: servlets attributes

public class Servlet1 extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ServletContext sc  = (ServletContext) getServletConfig().getServletContext();
        out.println("sc  = " + sc);
    }

...

> The result for internal call (http://local-server-ip:8080/prj/Servlet1) :
  sc  = org.apache.catalina.core.ApplicationContextFacade@1d57f3c

> The result for external call (http://example.com/prj/Servlet1) :
  sc  = org.apache.catalina.core.ApplicationContextFacade@135542b

为什么他们不一样?如果它们不同,我们怎么能得到一个应该是应用程序的ServletContext属性?

1 个答案:

答案 0 :(得分:0)

由于这两个访问来自不同的URL,因此servlet上下文不应该是相同的。如果您遇到类似问题,请在访问项目和项目源时使用相同的URL。这也将避免Ajax调用的安全问题。