如何在Servlet 2.4版的init()方法中获取ContextPath [英] How to get ContextPath in init() method of Servlet version 2.4

查看:185
本文介绍了如何在Servlet 2.4版的init()方法中获取ContextPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用2.4美元的 Servlet ,我需要通过<$ c $获取 ContextPath c> init()在服务器启动时调用的方法,所以我没有任何 Request对象可以调用 getContextPath()并且因为Servlet版本我在 ServletContext 中没有 getContextPath()方法。

I'm using version 2.4 of Servlet and I need to get the ContextPath through the init() method which is called on server start, so I don't have any Request object that could call getContextPath() and because the Servlet version I do not have getContextPath() method in the ServletContext either.

有没有办法以某种方式获得 ContextPath()

Is there a way to get this ContextPath() somehow ?

推荐答案

可以在多个不同的上下文路径上发布一个Web应用程序,因此 上下文路径(单数)仅在特定请求的上下文中有意义。 Servlet 2.5将 getContextPath()添加到 ServletContext ,指定返回此Web应用程序的主上下文路径,但在早期的规范版本中,没有与容器无关的方式来访问这些信息。

One web application can be published at several different context paths, so the context path (singular) is only meaningful in the context of a particular request. Servlet 2.5 added getContextPath() to ServletContext, specified to return the "primary" context path for this web application, but there's no container-independent way to access this information in earlier spec versions.

可能有些技巧适用于某些容器,例如在Tomcat上 ServletContext.getResource()方法返回带有自定义方案的URL,格式为 jndi:// hostname / context / ... 。因此,您可以使用

There may be tricks that work for certain containers, for example on Tomcat the ServletContext.getResource() method returns URLs with a custom scheme, of the form jndi://hostname/context/.... Thus you may be able to use

ctx.getResource("/").getPath()

获取Tomcat上的上下文路径(或者可能是 getResource(/ WEB-INF / web.xml) )并修剪尾部,因为 getResource()被指定返回 null if你问它一个不存在的文件)。您将不得不尝试使用不同的容器来查找适用于这些容器的类似技巧。

to get the context path on Tomcat (or possibly getResource("/WEB-INF/web.xml") and trim off the tail, as getResource() is specified to return null if you ask it for a file that does not exist). You will have to experiment with different containers to find similar tricks that work on those.

这篇关于如何在Servlet 2.4版的init()方法中获取ContextPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆