Suppose we have 2 pages in the root path of our application:
index.jsp
has the following content:
<ul>
<li>
<a href="IndexServlet/requests?url=relativa">URL relativa</a>
</li>
<li>
<a href="IndexServlet/requests?url=relativa-slash">URL relativa con slash</a>
</li>
<li>
<a href="IndexServlet/requests?url=contexto">URL con contexto</a>
</li>
<li>
<a href="IndexServlet/requests?url=absoluta">URL absoluta</a>
</li>
</ul>
The servlet configuration in web.xml
has:
<servlet>
<servlet-name>IndexServlet</servlet-name>
<servlet-class>jsp.ejemplo.IndexServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IndexServlet</servlet-name>
<url-pattern>/IndexServlet/requests</url-pattern>
</servlet-mapping>
And finally servlet IndexServlet
has the following method to respond to requests GET
:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = request.getParameter("url");
if(url.equals("relativa")) {
response.sendRedirect("otro.jsp");
} else if(url.equals("relativa-slash")) {
response.sendRedirect("/otro.jsp");
} else if(url.equals("contexto")) {
response.sendRedirect(request.getContextPath() + "/otro.jsp");
} else if(url.equals("absoluta")){
response.sendRedirect("http://localhost:7001/jsp-app/otro.jsp");
} else {
response.sendError(500, "parametro url no valido");
}
}
The result of navigating through the different links will be:
-
Relative URL: HTTP 404. The browser tries to access the url
"http://<Servidor>/jsp-app/IndexServlet/otra.jsp"
-
Relative URL with slash: HTTP 404. The browser tries to access the url
"http://<Servidor>/otra.jsp"
-
URL with context: OK. request.getContextPath()
returns the context of the application /jsp-app
and therefore the redirect is instructed to send to the relative url
"http://<Servidor>/jsp-app/otra.jsp"
-
Absolute URL: OK. The complete absolute url is sent to the redirect, so it is not translated when it is sent to the browser.
"http://<Servidor>/jsp-app/otra.jsp"
The context of the application depends on the application server used, in weblogic for example it is defined in weblogic.xml
as:
<context-root>/jsp-app</context-root>