How to Get Default Context Root URL in JSP

Posted on

This article focus on the discussion about how to get default context root URL in JSP. Basically, not only the default context root, but the whole URL which is used to access main page. There is actually a connection with the article titled ‘How to Set Default URL of A Web-based Java Application Deployment in JSP’ in this link. The default URL is actually the context root URL set in the configuration of the server’s deployment descriptor file. So, what is actually the main purpose to get default context root URL in JSP page file ?.

It is quite important to get it for an example to define the target action of a form submitted. Below is an example of the snippet code from the script exist in JSP page file :

<form action="/user-add" method="post" class="form-signin">

<h1 class="h3 mb-3 font-weight-normal">Add User</h1>
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" id="inputUsername" class="form-control"
placeholder="Hostname" required autofocus name="hostname">

<label for="inputPassword" class="sr-only">Password</label>
<input type="text" id="inputPassword" class="form-control"
placeholder="Password" required name="password">

<input type="hidden" name="action" value="server-add"/>

<button class="btn btn-lg btn-primary btn-block" type="submit">

<p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p>

So, it is not enough only definition ‘/user-add’ in the value of the action’s attribute of the tag form. There is an additional part of the URL which is the most important one stating the full path of the actual Java Application Server address including an additional port defined such as port 8080. It is the variable which is containing the full path URL without the context-root value for an example : “http://localhost:8080”.

In order to get the value mentioned above, there is a special variable which can be useful if it is inserted as part of the value of the action’s attribute in the tag form. Just edit the snippet code and add the following script :


It will print the value or in other words, it represents the value of “http://localhost:8080”. So, in the snippet code or in the script, just insert and add it as part of the URL as whole as shown below :

<form action="${pageContext.request.contextPath}/user-add" method="post" class="form-signin">

Leave a Reply