Tomcat: recuperare il contextPath dell’applicazione

Il contextPath è il percorso fisico dove si trova il deploy di una applicazione web. Sotto tomcat, ad esempio, si riferisce alla posizione su filesystem della cartella webapps in aggiunta al nome dell’applicazione.
Se abbiamo una webapp che si chiama pippo, avremo, ad esempio:

/var/lib/tomcat7/webapps/pippo

Per recuperarlo all’interno di una jsp o di una servlet basta usare il ServletContext. All’interno di una servlet:

public class MiaServlet extends HttpServlet {
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
                [...]
		ServletContext servletContext = getServletContext();
		String contextPath = servletContext.getRealPath(File.separator);
                [...]
	}
}

mentre da una jsp:

<%= request.getContextPath().getRealPath(File.separator) %>

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>