example java java-ee

java - example - jstl



Root URl del servlet (5)

Quiero obtener la URL raíz de mi aplicación web desde uno de los servlets.

Si despliego mi aplicación en "www.midominio.com", quiero obtener la url raíz como " http://www.midominio.com ".

Lo mismo si lo despliego en un servidor tomcat local con un puerto 8080 debería dar http://localhost:8080/myapp

¿Alguien puede decirme cómo obtener el URL raíz de mi aplicación web desde servlet?

public class MyServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String rootURL=""; //Code to get the URL where this servlet is deployed } }


  1. Escriba un scriptlet en el archivo de bienvenida para capturar la ruta raíz. Supongo que index.jsp es el archivo predeterminado. Pon el siguiente código en ese

    <% RootContextUtil rootCtx = RootContextUtil.getInstance(); if( rootCtx.getRootURL()==null ){ String url = request.getRequestURL().toString(); String uri = request.getRequestURI(); String root = url.substring( 0, url.indexOf(uri) ); rootCtx.setRootURL( root ); } %>

  2. Use esta variable donde sea necesario dentro de la aplicación llamando directamente al valor como

String rootUrl = RootContextUtil.getInstance().getRootURL();

NOTA: No necesita preocuparse por protocolos / puertos / etc. Espero que esto ayude a todos


¿Te das cuenta de que el cliente URL ve (y / o escribe en su navegador) y la URL servida por el contenedor en el que se implementó tu servlet puede ser muy diferente?

Sin embargo, para obtener lo último, tiene algunos métodos disponibles en HttpServletRequest :

  • Puede llamar a getScheme() , getServerName() , getServerPort() y getContextPath() y combinarlos usando los separadores apropiados
  • O puede llamar a getRequestURL() y eliminar getServletPath() y getPathInfo() de él.


Esta función te ayuda a obtener tu URL base de HttpServletRequest :

public static String getBaseUrl(HttpServletRequest request) { String scheme = request.getScheme() + "://"; String serverName = request.getServerName(); String serverPort = (request.getServerPort() == 80) ? "" : ":" + request.getServerPort(); String contextPath = request.getContextPath(); return scheme + serverName + serverPort + contextPath; }


public static String getBaseUrl(HttpServletRequest request) { String scheme = request.getScheme(); String host = request.getServerName(); int port = request.getServerPort(); String contextPath = request.getContextPath(); String baseUrl = scheme + "://" + host + ((("http".equals(scheme) && port == 80) || ("https".equals(scheme) && port == 443)) ? "" : ":" + port) + contextPath; return baseUrl; }