I have some JavaScript that is making an Ajax call to a relative url (using jQuery).
var servletUrl = "someservlet";
$.ajax({
type: "POST",
url: servletUrl,
success: function(response) {
// ...
}
});
Where "someservlet"
is:
@WebServlet("/someservlet")
public class SomeServlet extends HttpServlet
I use this same script in multiple pages. When used from a page that is in the servlet context root, then the relative url resolves relative to the servlet context root, which is correct. When used from a page that is in a subfolder the URL resolves relative to the subfolder, which will return 404 error.
I would like to be able to reuse this JavaScript without having to modify it depending on the type of page that it is used within. Ideally, I need the equivalent of the JSTL's <c:url>
tag. Is there anything in JavaScript that allows me to create URLs relative to the servlet context root?
Several options:
Set a HTML <base>
element with that value (note: has its own advantages and disadvantages)
<head>
<base href="${pageContext.request.contextPath}/" />
...
</head>
and then in JS:
var contextPath = $("base").attr("href");
var servletUrl = contextPath + "someservlet";
// ...
Or set a data attribute somewhere
<html data-contextPath="${pageContext.request.contextPath}/">
...
</html>
and then in JS:
var contextPath = $("html").data("contextPath");
var servletUrl = contextPath + "someservlet";
// ...
Or set a global JS variable with that value (poor practice):
<head>
...
<script>var contextPath = "${pageContext.request.contextPath}/";</script>
</head>
and then in JS:
var servletUrl = contextPath + "someservlet";
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With